Search code examples
reactjsasynchronoussetstate

How to return the index from two array?


I have two array my desired result is to return the index from matching values. How to do that?

For instance I have these two array:

const arr1 = [ monkey, lion, giraffe, bear, ant, fish, dinosaur ]

cosnt arr2 = [ lion, giraffe, bear ]

How to return the result as the index from matching values?


Solution

  • You can try like this.

    const arr1 = [ 'monkey', 'lion', 'giraffe', 'bear', 'ant', 'fish', 'dinosaur' ]
    const arr2 = [ 'lion', 'giraffe', 'bear' ];
    let index = [];
    
    arr2.forEach(function(a,i){
      index.push(arr1.indexOf(a));
    });
    console.log(index);
    
    //another way using map function
    let result = arr2.map((a,i)=>{
       return arr1.indexOf(a);
    })
    console.log(result);