indexOf depending on two keys

Viewed 84

How can I see the indexOf when two keys have a certain value, in an object?

let myObj = {
"value1":[1,2,3],
"value2":[2,3,4]};

I would like to get the index of when myObj.value1==1 && myObj.value2==2, for instance. I can't seem to find the way to do it.

edit : well there could be :

if (myObj.value1.indexOf(1) == myObj.value2.indexOf(2)) {
commonIndex = myObj.value1.indexOf(2);}

But is there some more elegant way?

Also, how could I manage the situation where the value appears several times?

like here :

let myObj = {
"value1":[1,1,1,2,3,4,5],
"value2":[2,3,4,5,6,7,8]}

And I would want the case where value1==1 and value2==3.

3 Answers

You can use this. It is more efficient. As indexOf takes O(n) time so using it once is better than twice.

var ind = myObj.value1.indexOf(1);
if ( myObj.value2[ind] === 2) {
    commonIndex = ind;
}

Edit: As I saw you edited the question and arrays can have multiple occurences of those elements. Here is my solution:

myObj.value1.forEach(function(val, ind){
    if(val ===1 & myObj.value2[ind] === 2){
        commonIndex = ind;
    }
})

This if is not good you could do:

if (myObj.value1.includes(1) === myObj.value2.includes(2)) {
commonIndex = myObj.value1.indexOf(2);}

U can use below code to get key from value of object

function getKeyByValue(object, value) {
  return Object.keys(object).find(key => object[key] === value);
}

Related