Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EcmaScript6 findIndex method, can it return multiple values?

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

like image 262
CesarCedanoV Avatar asked Jul 03 '18 15:07

CesarCedanoV


3 Answers

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);
like image 25
Eddie Avatar answered Sep 22 '22 15:09

Eddie


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));
like image 162
palaѕн Avatar answered Sep 21 '22 15:09

palaѕн


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);
like image 31
amrender singh Avatar answered Sep 23 '22 15:09

amrender singh