I'm trying to return the index of an item that meets a certain condition from within an Array.filter
method, but I still keep getting an array of actual values instead of the indexes of the values I want.
Example:
var seq = [3, 4, 1, 2, 1];
seq.filter((curr, index) => {
if (seq[index + 1] < seq[index]) {
return index;
}
});
// returns [4, 2]
// want to return [1, 3] (the indexes of 4 & 2)
Is there a more efficient method I can use? I'm trying to avoid using a for loop. Thanks.
You can use reduce
here
var seq = [3, 4, 1, 2, 1]; var result = seq.reduce((ar, curr, index) => { if (seq[index + 1] < seq[index]) ar.push(index); return ar; }, []); console.log(result)
You can use filter with an array of the indices and the right test for the return
var seq = [3, 4, 1, 2, 1], result = seq.map(function (_, i) { return i; }).filter(function (i) { return seq[i - 1] < seq[i]; }); console.log(result);
The better solution would be a loop with forEach
var seq = [3, 4, 1, 2, 1], result = []; seq.forEach(function (a, i) { seq[i - 1] < a && this.push(i); }, result); console.log(result);
It's not a bad idea to use a for loop in this case. I personally think it's cleaner and more efficient.
let seq = [3, 4, 1, 2, 1];
for (let i = 0; i < seq.length; i++) {
if (seq[i + 1] < seq[i]) {
continue;
}
seq.splice(i, 1);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.