I have a two dimensional array that in turn has an object with an additional array.
I want to filter the array and return a new array with the index that matches the criteria with the object.
For example:
One array: gp[0][0].pts = [10,5,40,30,95,5,11,85];
I want to search the array and return values above or equal to 20. This would be [40, 30, 95, 85];
I want the new array to return the indexes for these, so in this case it would be [2,3,4,7]
The code below returns the correct numbers but I want the indexes instead.
Thanks in advance.
const gp = [
[{
"pts": [10, 5, 40, 30, 95, 5, 11, 85]
}, {
"pts": [2, 1, 4]
}, {
"pts": [14, 22, 41, 23]
}]
];
for (let n = 0; n <= 2; n++) {
const race = gp[0][n].pts.filter(v => +v >= 20).map(Number);
if (race.length) {
console.log(`race at n=${n}: ${race}`);
};
};
5
Answers
You could achieve that with the following
1-
Map each value to an object containing both value and index2-
Filter objects with value >= 203-
Map back to indicesFirst, map the arrays to [element, index] pairs. Then filter, then extract just the indices.
Instead of first filtering, and then mapping, first map your "number" to a "number and index", then filter:
Or if you know your downstream code will never need both the index and the associated value, return
{n: result.map(({ index }) => index)}
instead, of course.Alternatively, use
reduce
as mentioned by Alexander NenashevIf you want a performant fast solution, use
Array#reduce()
and collect indices without intermediate arrays (waste of time & space):And a benchmark:
And here is another solution on the basis of
Array.forEach()
andArray.reduce()
: