Mike Irish
Mike Irish

Reputation: 960

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);

Upvotes: 3

Views: 1305

Answers (3)

DecPK
DecPK

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

Maradox
Maradox

Reputation: 640

Short answer is Yes, you can.

  1. You can filter and modify the array in only one go.

  console.log(
  [243 * 10, -132, 112, 40, -96]
  .filter((age, index, arr) => { 
         arr[index+1] *= 10;
         return age > 0;
 }))

  1. But I think we should avoid it as much as we can. Because it mutates the original array.

Upvotes: 1

Costa
Costa

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

Related Questions