Check if a value exists in a 2D array

I have a 2d array in the format

emi_309 | present | weak   | 6
emi_310 | present | strong | 9
emi_319 | present | medium | 8
emi_315 | present | weak   | 5

I want to check if a value exists in the first column using a simple function

For example, check if emi_77 exists in the first column

I came across $.inArray(value, array), but this function is only for the 1st array.

Is there something similar for a 2d array

+5
source share
4 answers

Yes, if you do a combination of $.inArrayand $.map:

if ($.inArray(value, $.map(arr, function(v) { return v[0]; })) > -1) {
    // ...
}
+6
source

Can be used $.grepto create a new array and check length

var val='emi_77';
if( $.grep( twoDarray, function(item){ return item[0]===val; }).length){
  /* item exists*/
}

$.grep will not affect the original array

API Link: http://api.jquery.com/jQuery.grep/

+1
source

, JQuery.

for (var i = 0; i <array.length; i++) {
        if(array[i][0] == 'emi_77'){
            alert("exists");
        }
}

, :

function IsIn2D(str,order,array){
  for (var i = 0; i <array.length; i++) {
        return array[i][order] == str;
  }
}

Where;
 an array is the array you want to find. str is the string you want to check if it exists - the order of the string in internal arrays,

for example, by applying this to a two-dimensional array of questions:
emi_309 | present | weak | 6
emi_310 | present | strong | 9
emi_319 | present | middle | 8
emi_315 | present | weak | 5

IsIn2D('emi_77',0,array); /*returns false*/
IsIn2D('emi_315',0,array); /*returns true*/
+1
source

Check out these methods for searching from a 2D array. Just check with conversion to string and compare.

function isArrayItemExists(array , item) {
    for ( var i = 0; i < array.length; i++ ) {
        if(JSON.stringify(array[i]) == JSON.stringify(item)){
            return true;
        }
            }
            return false;
}
0
source

All Articles