TheWebs
TheWebs

Reputation: 12923

easiest way to see if array has array? Javascript

the only way I can think to do this is to do something like:

for current array length,
  for array to check length
   if current array i === array to check i
      true

Essentially I have the following:

arr = [[1,2], [0,3]];

When I want to add another array to this arrays: [1,2] I need to first see if it exists, if it does do not push it on to the array, if it doesn't then push it.

Is there some really simple, clean readable way to check if an array exists in an array of arrays before pushing it on to the list of elements?

Update:

it should be pretty simple, you have array:

arr = [[1,2], [0,3]];

You try and push:

[1,2]

Nothing happens.

You try and push: [4,6]. New array: [[1,2], [0,3], [4,6]];

Upvotes: 3

Views: 94

Answers (3)

Brett DeWoody
Brett DeWoody

Reputation: 62773

If you know your array arr contains only integers and arrays, a simple check to see if the array matches the flattened array will indicate if the array contains inner arrays.

var arr = [1,2,3,[4,5],6];

if (JSON.stringify(arr) === JSON.stringify([].concat.apply([], arr))) {
  // Does not contain an array
}

The snippet [].concat.apply([], arr) flattens the array arr.

Upvotes: 1

Ananth
Ananth

Reputation: 4397

Using underscore you can do this:

Initial approach:

    var i = _.findIndex(arr, function (e) {
         return (e.join(',') === arr_elem.join(','));
    });

    if (i === -1) {
        arr.push(arr_elem);
    }

EDIT Considering performance (Also read the comments here), it would be better to check array equality using a brute loop approach:

function arraysEqual(arr1, arr2) {
    if(arr1.length !== arr2.length)
        return false;
    for(var i = arr1.length; i--;) {
        if(arr1[i] !== arr2[i])
            return false;
    }

    return true;
}

var i = _.findIndex(arr, function (e) {
     return arraysEqual(arr_elem, e);
});

if (i === -1) {
    arr.push(arr_elem);
}

Upvotes: 0

Amit
Amit

Reputation: 46323

Since the complexity is limited, a simple solution exists:

function maybePush(to, val) {
  if(!to.some(function(curr) {
      return curr.length !== val.length ||
        curr.some(function(v, i) { return val[i] === v; });
    })) {
     to.push(val);
  }
}


arr = [[1,2], [0,3]];
maybePush(arr, [1,2]);
maybePush(arr, [5,6]);
console.log(arr);

You'd probably want to add some guards, check that what you expect to be an array really is an array and so on (left out for clarity)...

The idea is simple, check if any of the values of the outer array is equal to the val array, using an iterative comparison.

Upvotes: 3

Related Questions