You can achieve what you want in this way:
You can check if the value is already there in your final array using 'some'
data = [{Id: 1, Definition: "House"}, {Id: 1, Definition: "House"}]
const finalOut = []
data.forEach((value) => {
if (!finalOut.some(x=> (x.Id === value.Id || x.Definition === value.Definition)))
{
finalOut.push(value)
}
})
You can also achieve this by 'reduce' in clean and elegant way:
const finalOut2 = data.reduce((acc, cur) => acc.some(x=> (x.Id === cur.Id || x.Definition === cur.Definition)) ? acc : acc.concat(cur), [])
As suggested by @Ezequiel using some
inside forEach
or reduce
making the time complexity of order of n square. For smaller sets of data using reduce
and some
is an elegant approach. But if you are dealing with arrays of very large length, you must avoid order of n square time complexity Here is one such approach with filter
:
//Here storing every value of data is inside lookupObj after filtering it.
//And checking if value is filtered based on if key of the value inside lookupObj
const lookupObj = {}
const finalOut3 = data.filter(
x => {
const is_unique = !(lookupObj[`Id_${x.Id}`] || lookupObj[`Id_${x.Definition}`])
lookupObj[`Id_${x.Id}`] = true
lookupObj[`Id_${x.Definition}`] = true
return is_unique
}
)