1

Suppose I have a multi dimensional array in JavaScript:

var arr = [
    ['cat','23','5123'],
    ['dog','53','522'],
    ['bird','335','512'],
    ['horse','853','152'], 
    ['monkey','13','5452']
];

And I want to get the index of the array in arr that contains horse in the first index (output should be 3).

I can do this in the following way:

var index_i_need;

for(var i in arr){

    if(arr[i][0]==='horse') {

        index_i_need = i;
        break;
    }
}

console.log(index_i_need);  // 3
console.log(arr[index_i_need]); // ['horse','853','152']

But this isnt scaleable.

Id like to have some more direct method like indexOf(), for instance.

I know findIndex() takes a callback function but I havent been able to apply it correctly.

Any suggestions?

1
  • arr.findIndex(sa => sa[0] === "horse"); Commented May 27, 2017 at 7:07

1 Answer 1

2

You can use a dynamic find function, findByAnimal, to use in findIndex

function findByAnimal(animal) {
  return function(innerArr){
    return innerArr[0] === animal
  }
}

arr.findIndex( findByAnimal('horse') )

The way findIndex works is each item in arr is passed into the callback, the first "truthy" return value from callback will yield the index, or -1 if no items return truthy.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @James, I quickly realized the same and updated the answer
@yevg if you found this useful, feel free to mark as answered or provide feedback. thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.