How to resolve array array only once?

I have an array with other arrays in it that were clicked. For instance:

const Arrays = [ [1,2,3], [4,5,6], [7,8,9], [2,1,3] ];
let myArr = [];

Arrays.map(arr => {
  if(myArr.indexOf(arr)){
   return
  }
  myArr.push(arr)
})

const myArr = [ [1,2,3], [4,5,6], [7,8,9], [2,1,3] ];

In this array, you see that there are two arrays with the same set of numbers 1, 2and 3. I want to somehow set the condition:

If this array already exists, do not add this array in any order to prevent this from happening. So when it comes in a loop that this set of numbers appears again, it just skips it.

+4
source share
4 answers

You can use some()and methods every()to check if the same array exists before push().

const myArr = [ [1,2,3], [4,5,6], [7,8,9] ];
let input =  [2,1,3]

function check(oldArr, newArr) {
  return oldArr.some(a => {
    return a.length == newArr.length &&
      a.every(e => newArr.includes(e))
  })
}

if(!check(myArr, input)) myArr.push(input)
console.log(myArr)
Run code
+5
source

temp sorted element with joined indexOf

const myArr = [ [1,2,3], [4,5,6], [7,8,9], [2,1,3],[6,5,4] ];
var newArr = [];
var temp = [];
for(let i in myArr){
  let t = myArr[i].sort().join(",");
  if(temp.indexOf(t) == -1){
    temp.push(t);
    newArr.push(myArr[i]);
  }
}
console.log(newArr);
+2

, , ,

[1, 1, 2]

[1, 2, 2]

which are different arrays.

For a working solution, I suggest using Mapand counting the occurrences of the same values ​​of the first array and subtracting the count of values ​​for another location.

As a result, return the check if all elements of the map are equal to zero.

function compare(a, b) {
    var map = new Map;
    a.forEach(v => map.set(v, (map.get(v) || 0) + 1));
    b.forEach(v => map.set(v, (map.get(v) || 0) - 1));
    return [...map.values()].every(v => !v);
}

var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [2, 1, 3], [1, 1, 2], [1, 2, 2], [2, 1, 1], [2, 1, 2]],
    unique = array.reduce((r, a) => (r.some(b => compare(a, b)) || r.push(a), r), []);

console.log(unique);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run code
+1
source

One way is to sort them numerically with .sort () and then compare them.

-1
source

Source: https://habr.com/ru/post/1690803/


All Articles