Skip to content
Advertisement

Get entire array of objects after mapping duplicates by a deep nested key

I have a huge nested array of objects and I want to filter and remove the duplicates, defined by the deep nested key uniqueId. With the following mapping I only get the values for the key uniqueId. But I need the entire array of objects m.

JS

var medis = [...new Map(m.map( o => [o['drugs'][0]['ingredient'].uniqueId, o['drugs'][0]['ingredient'].uniqueId])).values()];

Questions:

  1. How do I get the filtered array m?
  2. Is it possible within the mapping to keep only the last duplicate?

Thank you for your hints

Advertisement

Answer

I would rather use a Set to store the unique ids. You could use Reduce instead of map to do your filter. There you would validate if the set contains the object key in order to add to the accumulator array:

const uniqueKeys = new Set()

const medis = m.reduce((uniqueArray, o) => {
  const key = o['drugs'][0]['ingredient'].uniqueId
  if(uniqueKeys.has(key)) return uniqueArray
  uniqueKeys.add(key)
  uniqueArray.push(o)
  return uniqueArray
},[])

Note: If you want to store to the array each last object duplicated instead you can use ReduceRight instead.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement