How is it possible to map an array from a index and then map the rest based on a criteria.
const array = [4, 2, 8, 3, 4, 6];
const map = array.map((x, index) => {
if(x<8){
return index;
};
});
console.log(">> "+map);
// Output array should be [1,3,4,5]; * Final array will be a lot bigger;
For example I want to search the array from index 1 and then return the indexes of all values less than 8.
Is map the best way or is there another?
Any help / advice would be appreciated.
2
Answers
You can filter out the
undefined
values that are returned for the elements that don’t match the condition.Or do it in one loop using
reduce
.If you want to use an Array method like
.map()
wherein the return value is transformed (ex. current number to current index) but return nothing when a criteria is not met (ie filtering), try.flatMap()
..flatMap()
is.map()
but it will flatten the returned array (see.flat()
). The example below uses a ternary operator for the the criteria which means: