Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to only allow an array to be pushed into an array once?

I have an array that has other arrays in it which have been pushed in. For an example:

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 can see that there are two arrays with the same set of numbers 1, 2 and 3. I want to somehow set a condition saying:

If this array already exist then do not add this array in any order again to prevent this from happening. So that when it comes in the loop that this set of numbers comes up again it will just skip over it.

like image 999
Taylor Austin Avatar asked Mar 08 '23 08:03

Taylor Austin


2 Answers

You can use some() and every() methods to check if same array already 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)
like image 179
Nenad Vracar Avatar answered Mar 13 '23 09:03

Nenad Vracar


You can make temp array with sorted element with joined and check by 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);
like image 26
Niklesh Raut Avatar answered Mar 13 '23 10:03

Niklesh Raut