Home > Software engineering >  Find a certain index in an array based on a particular value
Find a certain index in an array based on a particular value

Time:04-20

I two arrays of equal size, but different values such that:

var1 = [1, 6, 9]

var2 = [4, 7, 3]

and another regular variable, var3 = null

I run an if statement to check if var3 (which will be given a value by an outside function) is equal to any of the elements in the var1 array. For example:

if var1.includes(var3) //let's say this returns true in this case...

then get the index of that matching element within the var1 array.

then, use this index number to look within the second array, var2, at that same index,

finally, get the value at that index in the var2 array


Essentially, what I'm trying to avoid is having a bunch of if statements such as:

If (var1.includes(var3)) && var3 == 1): get the element within var2 at the first index

elif (var1.includes(var3)) && var3 == 6): get the element within var2 at the second index

etc, etc.

Any suggestions appreciated I'm very new. Using a bunch of if statements seems wrong, so I feel there must be a better way to look inside one array, get an element and its index, and look inside another array at that same index to get that element. Maybe a dictionary would be easier? Not really sure....

CodePudding user response:

You can use indexOf.

var1 = [1, 6, 9]
var2 = [4, 7, 3]
var3 = 6

let index;
let secondVal

if (var1.includes(var3)) {
    index = var1.indexOf(var3)
    secondVal = var2[index]
    // should print out 7
    console.log("secondVal")
}


CodePudding user response:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

Array.indexOf may be what you're looking for.

const temp = var1.indexOf(var3);
var2[temp];

If var3 is not in the first array, indexOf returns -1.

CodePudding user response:

I have an answer using loops. map function in javascript. This will reduce your if-else statement

var var3=6
var var1=[1,6,9]
var var2=[4,7,3]

var1.map((element,index)=>{
    if(element==var3){
        console.log(var2[index]);
    }
})
  • Related