Find and return array positions of multiple values JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We have to write a function, say findPositions() that takes in two arrays as argument. And it should return an array of the indices of all the elements of the second array present in the first array.

For example −

If the first array is [‘john’, ‘doe’, ‘chris’, ‘snow’, ‘john’, ‘chris’],
And the second array is [‘john’, chris]

Then the output should be −

[0, 2, 4, 5]

Therefore, let’s write the code for this function. We will use a forEach() loop here;

Example

const values = ['michael', 'jordan', 'jackson', 'michael', 'usain',
'jackson', 'bolt', 'jackson'];
const queries = ['michael', 'jackson', 'bolt'];
const findPositions = (first, second) => {
   const indicies = [];
   first.forEach((element, index) => {
      if(second.includes(element)){
         indicies.push(index);
      };
   });
   return indicies;
};
console.log(findPositions(values, queries));

Output

The output in the console will be −

[ 0, 2, 3, 5, 6, 7 ]
raja
Published on 25-Aug-2020 10:09:44
Advertisements