Get Indexes of Filtered Array Items
Solution 1:
Use a reducer.
var arr = [5, 10, 2, 7];
var newArr = arr.reduce(function(acc, curr, index) {
if (curr < 10) {
acc.push(index);
}
return acc;
}, []);
console.log(newArr);
Solution 2:
You can use a forEach
loop:
const arr = [5, 10, 2, 7];
const customFilter = (arr, min) => {
const result = [];
arr.forEach((element, index) => {
if (element < min) {
result.push(index);
}
});
return result;
}
console.log(customFilter(arr, 10));
Solution 3:
You can use array#reduce
and add indexes whose value is greater than 10.
var arr = [5, 10, 2, 7];
var indexes = arr.reduce((r, d, i) => d < 10 ? (r.push(i), r) : r , []);
console.log(indexes);