Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


    [ 
      ['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.)

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading