-2

I have an array with lists:

[ [ 1, 2 ], [ 3, 5 ], [ 2, 5 ], [ 3, 5 ], [ 1, 2 ] ]

The output im expecting is:

[ [ 1, 2 ], [ 3, 5 ] ]

Im not able to iterate and find duplicates when we have lists in an array.

Marcel Dz
  • 2,321
  • 4
  • 14
  • 49
  • 3
    What did you try to achieve this? – mykaf Oct 27 '22 at 21:13
  • 2
    Convert the nested arrays to JSON. Then use any algorithm for finding duplicate strings. – Barmar Oct 27 '22 at 21:37
  • 1
    The idea to find duplicate arrays (arrays that are equivalent to other arrays in the outer array) What constitutes equivalence of two arrays? @Barmar suggests that having the same in JSON encoding (maybe before or after sorting?) is a kind of equivalence. Deciding about this will make the problem pretty easy. – danh Oct 27 '22 at 21:39
  • duplicate [How to find the duplicates in a JavaScript Multidimensional array](https://stackoverflow.com/questions/20997127/how-to-find-the-duplicates-in-a-javascript-multidimensional-array) – pilchard Oct 27 '22 at 22:52

2 Answers2

1

You can compare two arrays using JSON.stringify. First, call the reduce method on the original array starting with an empty arr as the accumulator, then push each item of the original array inside the acc array only if it hasn’t already been pushed inside acc. In order to check if acc doesn’t already contain that item(array), you can use a method like some and see if any array inside the acc array, is equal to the current array or not.To compare the arrays use JSON.stringify.

const data = [ [ 1, 2 ], [ 3, 5 ], [ 2, 5 ], [ 3, 5 ], [ 1, 2 ] ]
const includesArray = (arr1, arr2) =>
  arr1.some(item=>
   JSON.stringify(item)==JSON.stringify(arr2));

const result=data.reduce((acc,item)=>
!includesArray(acc,item)?
[...acc,item]:
acc,[]);
console.log(result);
jessica-98
  • 609
  • 1
  • 6
1

I made the logic, maybe inefficient but it works. Here's the code:

const sameCombi = (arr) => {
    let result = []
    arr.forEach((ele) => {
        let same = arr.filter((val) => val.join() === ele.join())
        if (result.find((valRes) => valRes.join() === ele.join())) return false
        if (same.length > 1) result.push(ele)
    })
    return result
}

console.log(
    sameCombi([
        [1, 2],
        [3, 5],
        [2, 5],
        [3, 5],
        [1, 2]
    ])
)
Fauzan DP
  • 51
  • 4