Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to filter and modify the contents of a Javascript array in one go?

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);
like image 956
Michael Grinnell Avatar asked Oct 14 '25 14:10

Michael Grinnell


2 Answers

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);
like image 80
decpk Avatar answered Oct 17 '25 02:10

decpk


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);
like image 42
Costa Avatar answered Oct 17 '25 02:10

Costa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!