-2

I have a big set of objects in javascript array. I Need to find all duplicate object having same name.

e.g.

values = [
    { name: 'Name1', index:0 },
    { name: 'Name2', index:1 },
    { name: 'Name1', index:2 },
    { name: 'Name2', index:3 },
    { name: 'Name1', index:4 },
]

What I expect is a array having two objects

values = [
    { name: 'Name1', index:2 },
    { name: 'Name2', index:3 },
    { name: 'Name1', index:4 }
]

because these are the duplicates.

Garuda
  • 385
  • 5
  • 17
  • Check this: http://stackoverflow.com/questions/840781/easiest-way-to-find-duplicate-values-in-a-javascript-array and that: http://stackoverflow.com/questions/9229645/remove-duplicates-from-javascript-array –  Sep 23 '16 at 14:33

2 Answers2

0

New additions to ES6 are really interesting here, such as the Set class. This code does not modify your initial object, but it's simple to adapt.

function unique(values) {
  const knownNames = new Set();
  const result = [];

  for (const value of values) {
    if (!knownNames.has(value.name)) {
      knownNames.add(value.name);
      result.push(value);
    }
  }

  return result;
}
Aurelien Ribon
  • 7,548
  • 3
  • 43
  • 54
0

This probably isn't the most efficient way and you should probably use the Set if you don't need to worry about IE9

values = [
    { name: 'Name1', index:0 },
    { name: 'Name2', index:1 },
    { name: 'Name1', index:2 },
    { name: 'Name2', index:3 },
    { name: 'Name1', index:4 },
]

// check an array for an object with a matching name property
// `some` will return early so you don't need to process the whole array
// if a match is found
const contains = (name, arr) => arr.some(item => item.name === name)

// reduce the array to keep the value contained
const output = values.reduce((acc, value) => {
  if (!contains(value.name, acc)) {
    return acc.concat(value)
  }
  return acc
}, [])

console.log('first unique', output)
synthet1c
  • 6,152
  • 2
  • 24
  • 39