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 to iterate through an array of arrays to find duplicates

I have a problem while trying to iterate through an array of arrays. As it was suggested, I created two loops – outer and inner. I have to compare each item of each array with each item of other arrays to find out if duplicate are presented. Which method should I use for it?

  const arr = [
  ['a', 'b', 'm'],
  ['g', 'o', 'a', 'b'],
  ['w', 'o', 'u', 'k', 'a', 'b']
  ]

  const countTimes = arr => {
  arr.forEach(el => {
    for (k = 0; k < arr.length; k++) {
    for (i = 0; i < el.length; i++) {
       console.log(arr[k][i])
    }
   }
 })
}

 countTimes(arr)

>Solution :

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

You can create a simple counter object (if you know python, this is similar to collections.Counter):

class Counter extends Map {
  update(values) {
    for (let val of values)
      this.set(val, 1 + (this.get(val) ?? 0))
  }
}

ARR = [
  ['a', 'b', 'm'],
  ['g', 'o', 'a', 'b'],
  ['w', 'o', 'u', 'k', 'a', 'b']
  ]

const tally = new Counter()

for (let subArray of ARR)
  tally.update(new Set(subArray))

for (let [element, count] of tally)
  if (count === ARR.length)
    console.log(element)

count === yourArrayOfArrays.length selects elements that appear in all arrays, you can replace it with count > 1 to find any duplicates.

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