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?
Notice that you have arrays with objects that have value properties repeated
values to idI 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)