Home > Mobile >  Check if two arrays are equal in an array of arrays in Javascript
Check if two arrays are equal in an array of arrays in Javascript

Time:10-19

I have this array

const array1 = [[1,2], [2,3], [1,2]]

I want to be able to get [1,2] as the output since it's a duplicate. I have tried:

array1.some((element, index) => {
    return array1.indexOf(element) !== index
});

and

array1.filter((item, index) => array1.indexOf(item) !== index)

both of them doesn't work since I think it's an array of arrays. Any help is deeply appreciated.

CodePudding user response:

You could use filter with findIndex rather than indexOf, comparing stringified versions of the elements of the array to find a match:

const array1 = [[1,2], [2,3], [1,2]]

const result = array1.filter((a, i, arr) => 
  arr.findIndex(aa => JSON.stringify(aa) == JSON.stringify(a)) !== i
  )
  
console.log(result)

If performance is an issue, run JSON.stringify on all elements first and then map JSON.parse to the result array. Note that since you are now searching for a JSON string you can use indexOf again:

const array1 = [[1,2], [2,3], [1,2], [3, 4], [3,2], [3, 4]]

const result = array1.map(JSON.stringify)
  .filter((a, i, arr) => arr.indexOf(a) !== i)
  .map(JSON.parse)
  
console.log(result)

CodePudding user response:

Stringify each array you iterate over, and use that as a key in an object. Increment the value whenever that key is found. After looping, look through the object for values higher than 1.

const array1 = [[1,2], [2,3], [1,2]];
const occurrencesByJSON = {};
for (const subarr of array1) {
  const key = JSON.stringify(subarr);
  occurrencesByJSON[key] = (occurrencesByJSON[key] || 0)   1;
}
const output = Object.entries(occurrencesByJSON)
  .filter(([json, count]) => count > 1)
  .map(([json, count]) => JSON.parse(json));
console.log(output);

  • Related