Home > other >  Get the element array position matching the query
Get the element array position matching the query

Time:10-29

I'm looping through an array of items to check the corresponding element in order to display them in the correct order.

const array1 = ["one", "two", "three", "four"]
const array2 = ["two", "three", "one", "four"]
 
      for (i = 0; i < array1.length; i  ) {
        console.log(array1);
         console.log(array1.filter((element) => array2.includes(element)));
       // here I'm trying to iterate through each element of array1 and find the corresponding element in array2.
   
      }

The expected output should be something like :

the corresponding array of array1[0] is array2[2],
the corresponding array of array1[1] is array2[1],
and so on.

CodePudding user response:

You can check the index of array1 against array2 with nested loop.

const array1 = ["one", "two", "three", "four"]
const array2 = ["two", "three", "one", "four"]
 
      for (i = 0; i < array1.length; i  ) {
       for (var j =0; j<array2.length; j  ){
                if (array1[i] == array2[j]){
                    console.log("the corresponding array of array1[" i "] is array2[" j "]")
            }
        }
   
      }
       

CodePudding user response:

You could do something like that:

const array1 = ["one", "two", "three", "four"]
const array2 = ["two", "three", "one", "four"]

for (const [a1Idx, a1] of array1.entries()) {
  const a2Idx = array2.indexOf(a1)
  if (a2Idx >= 0) {
    console.log(`The corresponding array of array1[${a1Idx}] is array2[${a2Idx}]`)
  }
}

The indexOf() method returns the index of the searched value, but -1 if the value was not found.

CodePudding user response:

is that what you want?

let array1 = ["one", "two", "three", "four"]
let array2 = ["two", "three", "one", "four"]
 
array1.sort((o1,o2) => {
    let p1 = array2.findIndex((o) =>o === o1);
    let p2 = array2.findIndex((o) =>o === o2);
    return p1 < p2 ? -1 : (p1 > p2 ? 1 : 0);
}).forEach(o => console.log(o))   

  • Related