Reputation: 960
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);
Upvotes: 3
Views: 1305
Reputation: 25406
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);
Upvotes: 6
Reputation: 640
Short answer is Yes, you can.
console.log(
[243 * 10, -132, 112, 40, -96]
.filter((age, index, arr) => {
arr[index+1] *= 10;
return age > 0;
}))
Upvotes: 1
Reputation: 2954
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);
Upvotes: 3