Javascript 2d array indexOf

80,962

Solution 1

You cannot use indexOf to do complicated arrays (unless you serialize it making everything each coordinate into strings), you will need to use a for loop (or while) to search for that coordinate in that array assuming you know the format of the array (in this case it is 2d).

var arr = [[2,3],[5,8],[1,1],[0,9],[5,7]];
var coor1 = [0, 9];
var coor2 = [1, 2];

function isItemInArray(array, item) {
    for (var i = 0; i < array.length; i++) {
        // This if statement depends on the format of your array
        if (array[i][0] == item[0] && array[i][1] == item[1]) {
            return true;   // Found it
        }
    }
    return false;   // Not found
}

// Test coor1
console.log("Is it in there? [0, 9]", isItemInArray(arr, coor1));   // True

// Test coor2
console.log("Is it in there? [1, 2]", isItemInArray(arr, coor2));   // False

// Then
if (!isItemInArray(arr, [x, y])) {
   arr.push([x, y]);
}

This implementation loops and grabs every value. If you care about performance you can do more complicated things like sorting the original array by the first index and then using binary search on the first index.

Another way is to bucket the first coordinate of each item in the array in an object (like a hashtable) and bucket the second value in each of those buckets to reduce search times; more info here http://en.wikipedia.org/wiki/Bucket_sort.

Otherwise this is probably good enough for what you need.

Solution 2

Working js fiddle

for(var k = 0; k < arr.length; k++){
    if(arr[k][0] == x && arr[k][1] == y){
        found = true;
    }
}

Much more of a hacky way than a simple index of, but it works

Solution 3

Not a complete answer just a side note that may help.

Use Lodash

This method will get you the position of a value within a 2 dimensional array

let a = [ [ 'bird' ], [ 'cat' ], [ 'dog' ], [ 'cow' ], [ 'bird' ] ];
let b = _.findIndex(a, function(el) { return el[0] == 'cow'; });
console.log(b);//answer is 3

As mentioned earlier you need a nested loop for traversing through the array.

Solution 4

Very simple without indexOf...

var arr = [[2,3],[5,8],[1,1],[0,9],[5,7]];
const isDup = (x,y) => {
   arr.find(it => JSON.stringify(it) == JSON.stringify([x,y])) == undefined ? arr.push([x,y]) : null
}

console.log(isDup(2,3)) /* Does not add */
console.log(isDup(1,2)) /*Does add*/
console.log(arr) /*Confirmation*/

Solution 5

Here's what I implemented

getIndexOfArray(array: any[], findArray: any[]): number{
  let index = -1;
  array.some((item, i)=>{
    if(JSON.stringify(item) === JSON.stringify(findArray)) {
      index = i;
      return true;
    }
  });
  return index;
}

here array is the array in which we need the index and findArray is the array whose index will be returned.
Note: This function will return only the first occurrence of findArray array insight array array.

Share:
80,962
phoeberesnik
Author by

phoeberesnik

Updated on November 19, 2021

Comments

  • phoeberesnik
    phoeberesnik over 2 years

    I have a 2d array like this:

    var arr = [[2,3],[5,8],[1,1],[0,9],[5,7]];
    

    Each index stores an inner array containing the coordinates of some element.

    How can I use Array.indexOf() to check if the newly generated set of coordinates is already contained in arr? I want to push into arr if only the coordinate is NOT a duplicate.

    Here is my attempt that didn't work:

    if (arr.indexOf([x, y]) == -1) {
        arr.push([x, y]);
    }
    

    It looks like indexOf() doesn't work for 2d arrays...

  • Jop Knoppers
    Jop Knoppers over 4 years
    I did want to have an index so I used: const find = this.pointList.findIndex(it => JSON.stringify(it) === JSON.stringify(item));
  • Alex Montoya
    Alex Montoya over 4 years
    I prefer to replace return el[0] == 'cow' to return el.includes('cow')
  • Apostolos
    Apostolos about 3 years
    I have copy-pasted and tried let b = _.findIndex(a, function(el) { return el[0] == 'cow'; }); and got ReferenceError: _ is not defined
  • Mendo
    Mendo about 3 years
    The underscore _ is a reference to Lodash. lodash.com
  • Gurupal singh
    Gurupal singh over 2 years
    @Mendo how can i conditionally change the style according to this ?