Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using indexOf method to find value in a 2D array

I want to ask a question that I have about a 2D array in JavaScript, similar to this:

var array = [[2,45],[3,56],[5,67],[8,98],[6,89],[9,89],[5,67]]

That is, on every index, I have an array as well.

Suppose that I have a value in my second index like 56, and I want the corresponding 1st index (i.e. 3 in above example).

I can do it using a loop (if no other option), but is there any better way?

Also, I know indexOf method in JavaScript, but it's not returning the index when I call it like this:

array.indexOf(56);

Any insight will be helpful.

like image 606
A_user Avatar asked Jun 18 '12 10:06

A_user


1 Answers

Use some iterator function.

filter allows you to iterate over an array and returns only the values when the function returns true.

Modern browsers way:

var arr = array.filter( function( el ) {
    return !!~el.indexOf( 56 );
} );
console.log( arr ); // [3, 56]
console.log( arr[ 0 ] ); // "3"

Legacy browsers way, using jQuery:

var arr = $.filter( array, function() {
    return !!~$.inArray( 56, $( this ) );
} );
console.log( arr ); // [3, 56]
console.log( arr[ 0 ] ); // "3"
like image 196
Florian Margaine Avatar answered Oct 09 '22 18:10

Florian Margaine