Here is a method to achieve your desired outcome:
To ensure that the value is not already present in your final array, you can utilize the 'some' function.
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)
}
})
An alternative method is using 'reduce', providing a cleaner and more elegant solution:
const finalOut2 = data.reduce((acc, cur) => acc.some(x=> (x.Id === cur.Id || x.Definition === cur.Definition)) ? acc : acc.concat(cur), [])
@Ezequiel suggested that employing some
within forEach
or reduce
results in a time complexity of n square. For larger datasets, it's advisable to avoid such time complexities. Here is an approach utilizing filter
:
//All values from data are stored in lookupObj after filtering.
//Checking if a value is filtered based on whether its key exists in 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
}
)