-1

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.

2 Answers 2

3

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.