While learning ES6 and i was trying to find the index of multiple items on an Array, but i just got the index of the first item that match with my condition or callback function.
Example: I have an Array with ages and i want the index of all the ages over or equals to 18.
let ages = [12,15, 18, 17, 21];
console.log(`Over 18: ${ages.findIndex(item => item >= 18)}`);
// output that i'm looking: [2,4]
// output that is coming: 2
So i want to understand if the Array.prototype.findIndex()
method just return the single index of the first item that match or -1
is any item satisfies the condition. And how can we do it using ES6?
Thanks
The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.
One option is using reduce
instead. Use concat
to add the index to accumulator if the number is greater than or equal to 18
let ages = [12, 15, 18, 17, 21];
let result = ages.reduce((c, v, i) => v >= 18 ? c.concat(i) : c, []);
console.log(result);
You can use .map()
method here like:
let ages = [12, 15, 18, 17, 21];
let indexes = ages.map((elm, idx) => elm >= 18 ? idx : '').filter(String);
console.log( indexes );
The syntax for the .map()
method is like:
var new_array = arr.map(function callback(currentValue[, index[, array]]) {
// Return element for new_array
}[, thisArg])
where we can use currentValue
and index
for our requirement.
And a generic function for it can be like:
const ages = [12, 15, 18, 17, 21];
const getAllIndexes = (arr, val) => {
return arr.map((elm, idx) => elm >= val ? idx : '').filter(String);
}
console.log(getAllIndexes(ages, 18));
console.log(getAllIndexes(ages, 17));
Simply use Array.reduce()
and make array of index of all ages greater than 18.
let ages = [12,15, 18, 17, 21];
var result = ages.reduce((a,curr,index)=>{
if(curr >= 18)
a.push(index);
return a;
},[]);
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With