1

This question is follow up for, Get the index of a multidimensional array with the value of a given string in javascript

I tried this answer,

var    a1 = [["present",["John","Josh","Jay"]],["absent",["May","Mary","Mary Jane"]]],
   a2 = [["J",["John","Josh","Jay"]],["M",["May","Mary","Mary Jane"]],["S",["Sally","Sam","Sammy Davis"]]],
getStatus = (a,n) => a.find(e => e[1].indexOf(n) !== -1)[0],
getIndex = (a,n) => a.findIndex(e => e[1].indexOf(n) !== -1);

console.log(getStatus(a1,"Mary"));
console.log(getIndex(a2,"Sammy Davis"));

This is working, but there are issues. What if the given string is not in the array? how to handle that? How to get all the indexes if there are more than one index that have a value of the given string?

For example, In the a1,

var a1 = ["present",["John","Josh","Jay"]],["absent",["May","Josh","Mary Jane"]]]

How to get 0,1? using getIndex()?

2
  • 4
    Not an answer, but I don't understand why you are using a multidimensional array for a1 instead of an object, seems like there is no gain. { present: ['John, 'Josh'], absent: ['May', 'Mary Jane']} would be easier to work with Commented Oct 18, 2016 at 18:38
  • JavaScript doesn't have multidimensional arrays, just arrays-of-arrays and such. Commented Oct 18, 2016 at 18:40

1 Answer 1

0

I have to agree with @Rob M.'s comment yet still you might do as follows;

var    a1 = [["present",["John","Josh","Jay"]],["absent",["May","Mary","Mary Jane"]]],
       a2 = [["J",["John","Josh","Jay"]],["M",["May","Mary","Mary Jane"]],["S",["Sally","Sam","Sammy Davis"]]],
getStatus = (a,n) => a.find(e => e[1].indexOf(n) !== -1)[0],
 getIndex = (a,n) => { var x = -1;
                       return [a.findIndex(e => (x = e[1].indexOf(n), x !== -1)),x];
                     };
console.log(getIndex(a2,"May"));
console.log(getIndex(a2,"Sammy Davis"));
console.log(getIndex(a2,"Daniel"));

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.