As the title states, I am wondering if it is possible to filter and array and then modify the values in one go? However, this is better explained with an example.
Imagine I have an array of numbers and I want to filter that array to include only positive numbers, then do some sort of calculation on the remaining numbers, say multiply by 10. Do I have to filter the array and then do an iteration to modify the values or can I do something like this?
const ages = [-243, -132, 112, 40, -96];
const filtered = ages.filter((number => (number > 0)) * 10);
You do this with single reduce function
const ages = [-243, -132, 112, 40, -96];
const result = ages.reduce((arr, num) => {
if (num > 0) arr.push(num * 10);
return arr;
}, []);
console.log(result);
or with single line function using flatMap
const ages = [-243, -132, 112, 40, -96];
const result = ages.flatMap((num) => (num > 0 ? [num * 10] : []));
console.log(result);
I don't think so.. I would do:
const ages = [-243, -132, 112, 40, -96];
const filtered = ages.filter(number => number > 0).map(x => x * 10);
console.log(filtered);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With