Skip to content
Advertisement

How can I extract from an array of arrays all the arrays that have the same value in their first field?

The following function elegantly finds duplicates in 1-dimensional arrays:

    const findDuplicates  = (dataArray) => {
      const duplicates = dataArray.filter((e, index, arr) => arr.indexOf(e) !== index);
      return (duplicates);
    };

When I send it (for example) this array [‘123456’, ‘787877’, ‘763223’, ‘787877’, ‘854544’] it returns [‘787877’].

What I need is something similar that works for a 2-d array so (for instance) inputting

    [ 
      ['123456', 'Smith'],
      ['787877',  'Jones'],
      ['763223', 'Waldo'],
      ['787877',  'Quagmire'],
      ['854544',  'Miller']
    ]

returns

[[‘787877’, ‘Jones’], [‘787877’, ‘Quagmire’]]

(To be clear, I’m only interested in whether the 1st field of each sub-array is a dupe.)

Advertisement

Answer

const findDuplicates = (dataArray) => {
  const duplicates = dataArray.filter((e, index, arr) => {
    return arr.some((val, i) => (index !== i && val[0] === e[0]))
  })
  return (duplicates);
};

const result = findDuplicates([
  ['123456', 'Smith'],
  ['787877', 'Jones'],
  ['763223', 'Waldo'],
  ['787877', 'Quagmire'],
  ['854544', 'Miller']
])

console.log(result)
Advertisement