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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With