Home > Mobile >  remove duplicates from multidimensional json array javascript
remove duplicates from multidimensional json array javascript

Time:03-15

Trying to remove duplicate object from arrays so that set of array contain only unique values. given input

var data=[
[{"name":"abc"}],
[{"name":"abc"}],
[{"name":"abc"},{"name":"def"}],
[{"name":"def"},{"name":"abc"},{"name":"efg"}],
[{"name":"abc"}]
]

expected output

result= [
[{"name":"abc"}],
[],
[{"name":"def"}],
[{"name":"def"},{"name":"efg"}],
[]
]

trying to de-duplicate object from all array(exists in all). object comparison rather than name attribute Any suggestions for logic here

CodePudding user response:

You can try to map the top level array and filter each array of item. Then you can declare a variable that will hold the unqiue values so that you have a basis for the checking.

const data = [
  // your multi-dimentional array here...
]

const unique = []
const filteredData = data.map(items => {
  const filteredItems = items.filter(item => {
    if (unique.includes(item.name)) {
       return false
    } else {
       unique.push(item.name)
       return true
    }
   })
  
  return filteredItems
})

console.log(filteredData)

CodePudding user response:

...more clunky stuff :

var data=[
[{"name":"abc"}],
[{"name":"abc"}],
[{"name":"abc"},{"name":"def"}],
[{"name":"def"},{"name":"abc"},{"name":"efg"}],
[{"name":"abc"}]
];

let newMap = new Map();

for(let item in data) {
  const [key, val] = [item, data[item]]
  addToMap(val)
}

function addToMap(entry) {
  if(entry.length > 1) {
    for(let item in entry) {
      addToMap([entry[item]])
    }
  } else {
    const item = entry[0];
    itemName = item?.name;
    console.log({item, itemName});
    
    if(!!itemName && !newMap.has(itemName)) {
      const key = itemName;
      const val = item;
      newMap.set(key, val);
    }
  }
}

let result = Array.from(newMap).flat()
.map(key => newMap.get(key) || [])
// .map(key => newMap.get(key) || null)
// .filter(item => item !== null)

console.log('RESULT ', result)
  • Related