DEV Community

bomoniyi
bomoniyi

Posted on

Performing array maths operations with .map() and .filter()

const numbers = [1, 2, 3, 4, 5, 6];

const doubledNumbers = numbers.reduce((acc, num) => {
  acc.push(num * 2);
  return acc;
}, []);
console.log('doubled numbers', doubledNumbers);
console.log('numbers', numbers);
Enter fullscreen mode Exit fullscreen mode

You can use .reduce()

const numbers = [1, 2, 3, 4, 5, 6];

const doubledNumbers = numbers.map(num => num * 2);
console.log('doubled numbers', doubledNumbers);
console.log('numbers', numbers);
Enter fullscreen mode Exit fullscreen mode

Or you can use a newer and easier method .map()

const numbers = [1, 2, 3, 4, 5, 6];

const greaterNumbers = numbers.filter(num => num > 3);
console.log(greaterNumbers);
Enter fullscreen mode Exit fullscreen mode

Use .filter() if you're dealing with operations that deal with boolean. For example >, =, ?, etc...

Top comments (0)