2

Supposed i have two array

// item01
[
    { value: "0", value: "01", display: "Jamsheer", key: "jam" },
    { value: "1", value: "02",  display: "Muhammed", key: "muh" },
    { value: "2", value: "03", display: "Ravi", key: "rav" },
    { value: "3", value: "04", display: "Ajmal", key: "ajm" },
    { value: "4", value: "05",  display: "Ryan", key: "rya" }
]

// item02
[
    { value: "0", value: "01", display: "Kamal" },
    { value: "1", value: "02", display: "Jamal"},
]

The final result I need is the difference between these arrays using id & value and show item02: display, ID & item01: key – the final result should be like this:

[
    { value: "0", value: "01", display: "Kamal",  key: "jam"},
    { value: "1", value: "02", display: "Jamal", key: "muh"},
]

i tried filter with some method but it didn't solved my problem. Is it possible to do something like this using reduce in JavaScript?

2
  • "i tried filter with some method but it didn't solved my problem. " Post the JavaScript see minimal reproducible example. Commented Mar 2, 2022 at 7:14
  • Btw objects cannot contain the same key value twice Commented Mar 2, 2022 at 7:28

1 Answer 1

4

Notice that you have arrays with objects that have value properties repeated

  • I have modified first values to id

I think that what you want is something like this:

// item01
const item01 = [
  { id: "0", value: "01", display: "Jamsheer", key: "jam" },
  { id: "1", value: "02",  display: "Muhammed", key: "muh" },
  { id: "2", value: "03", display: "Ravi", key: "rav" },
  { id: "3", value: "04", display: "Ajmal", key: "ajm" },
  { id: "4", value: "05",  display: "Ryan", key: "rya" }
]

// item02
const item02 = [
  { id: "0", value: "01", display: "Kamal" },
  { id: "1", value: "02", display: "Jamal"},
]

const item01Hash = item01.reduce((a, c) => {
  a[`${c.id}${c.value}`] = c
  return a
}, {})

const result = item02.reduce((a, c) => {
  const { key } = item01Hash[`${c.id}${c.value}`]
  return key
    ? [...a, { ...c, key }]
    : a
}, [])

console.log(result)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.