2

so I have a multidimensional array. I want to get the key of one of the sub arrays, given a value.

var MyArr = [];
MyArr[0] = ['cat','black',5]
MyArr[1] = ['dog','red',7]
MyArr[2] = ['pig','blue',4]

what I want to be able to do is use a value say 'blue' and have it return the key of 2 so that I could take that 2 and do something like MyArr[2][0] to get 'pig'

I couldn't quite get indexof to work correctly.

any thoughts?

Also has to be pure JS cannot use JQuery

1
  • If you always have exact same number of elements in all nested array then you can also use Math.floor( MyArr.flat().findIndex((val) => val === "blue") / MyArr.length ); Commented Jun 21, 2021 at 22:53

1 Answer 1

2

You can do it like this, using Array.findIndex() and Array.includes():

const arr = [
  ['cat','black',5],
  ['dog','red',7],
  ['pig','blue',4]
];

let i = arr.findIndex(a => a.includes('blue'));

console.log(i)

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

Comments

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.