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 :
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.