skip to Main Content

I’m trying to check whether a sub-array exists in an array so that I could discard or avoid adding.

For example

Let’s assume I have an array like this

[
  [-5, 0, 5], [-5, 2, 3], 
  [-3, 0, 3,], [-3, 1, 2], 
  [-1, -1, 2], [-1, 0, 1]
]

and got another pair as
[-3, 1, 2] to add but it’s already available in existing data so need to check and avoid adding.

What I have tried so far

let mapped = result.map(item => item.join());
let match = `${item1},${item2},${item3}`; // coming items => item1, item2, item3 
if(mapped.includes(match)){
 ...
} else {
 ...
}

Is this okay to use or any better way to check it when we have a huge amount of data?

3

Answers


  1. Using array methods .find() and .every():

    const 
          arr = [
            [-5, 0, 5], [-5, 2, 3], 
            [-3, 0, 3,], [-3, 1, 2], 
            [-1, -1, 2], [-1, 0, 1]
          ],
          
          input = [-3, 1, 2],
          
          isIn = (a,b) => b.find(x => x.every((y,i) => y === a[i]))?.length > 0;
          
    console.log( isIn(input, arr), arr.length );
    
    isIn(input, arr) || arr.push(input);
    
    console.log( arr.length );
    
    isIn([-3, 1, -2], arr) || arr.push([-3, 1, -2]);
    
    console.log( arr.length );
    Login or Signup to reply.
  2. I would just iterate over your array and check if an element is equal to the element you want to add. Assuming you are only dealing with numbers, you can check that by converting your array to a string.

    const data = [
      [-5, 0, 5],
      [-5, 2, 3],
      [-3, 0, 3],
      [-3, 1, 2],
      [-1, -1, 2],
      [-1, 0, 1]
    ];
    const toAdd = [-3, 1, 2];
    
    const isRowIncludedInMatrix = (matrix, row) =>
      matrix.some(r => r.toString() === row.toString());
    
    if (!isRowIncludedInMatrix(data, toAdd)) // => false -> don't push
      data.push(toAdd);
    Login or Signup to reply.
  3. If that is the only data you have to work with, a simple comparison might be best.

    The some() and every() functions will early exit:.

    function addIfNotExists(arrays, newArray) {
      if (!arrays.some(x => x.length === newArray.length && x.every((e, i) => e === newArray[i])))
        arrays.push(x);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search