Home > Software engineering >  How to get the same combinations in my array list
How to get the same combinations in my array list

Time:10-28

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.

CodePudding user response:

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

CodePudding user response:

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

  • Related