Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find and return array positions of multiple values JavaScript
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 ]
Alternative Approach Using filter()
We can also use the filter() method with map() to achieve the same result:
const values = ['michael', 'jordan', 'jackson', 'michael', 'usain',
'jackson', 'bolt', 'jackson'];
const queries = ['michael', 'jackson', 'bolt'];
const findPositionsAlt = (first, second) => {
return first
.map((element, index) => second.includes(element) ? index : -1)
.filter(index => index !== -1);
};
console.log(findPositionsAlt(values, queries));
[ 0, 2, 3, 5, 6, 7 ]
How It Works
The function works by iterating through each element in the first array using forEach(). For each element, it checks if that element exists in the second array using includes(). If found, the current index is pushed to the result array. This ensures all positions of matching values are captured, including duplicates.
Conclusion
Both approaches effectively find all positions of multiple values in an array. The forEach() method is more readable, while the filter/map combination offers a functional programming approach.
