Managing data with modern JavaScript: map, filter, reduce, find

.map()

// Your array of numbers
let numbers = [12, 23, 8, 19, 10];
var numbers_m2 = [];
for (i = 0; i < numbers.length; i++) {
numbers_m2.push(numbers[i] * 2);
}
console.log(numbers_m2);
let numbers = [12, 23, 8, 19, 10];
let numbers_m2 = numbers.map(function(number) {
return number * 2;
});
console.log(numbers_m2);
let numbers = [12, 23, 8, 19, 10];
let numbers_m2 = numbers.map(number => number * 2);
console.log(numbers_m2);

.filter()

let numbers = [12, 23, 8, 19, 10];
let numbers_less_15 = numbers.filter(function(number) {
return number <= 15;
});
console.log(numbers_less_15);
let numbers = [12, 23, 8, 19, 10];
let numbers_less_15 = numbers.filter(number => number <= 15);
console.log(numbers_less_15);

.reduce()

var numbers = [12, 23, 8, 19, 10];
var total = 0;
for (i = 0; i < numbers.length; i++) {
total += numbers[i];
}
console.log(total);
let numbers = [12, 23, 8, 19, 10];
let total = numbers.reduce((acc, cur) => acc + cur);
console.log(total);
let numbers = [12, 23, 8, 19, 10];
let total = numbers.reduce(function(acc, cur) {
return acc + cur;
});
console.log(total);

.find() & .findIndex()

let numbers = [12, 23, 8, 19, 10];
let index = numbers.findIndex(number => number >= 9 && number <= 11);
let val = numbers.find(number => number >= 9 && number <= 11);
console.log(`${index} = ${val}`); // 4 = 10

Summary

  • Map evokes a function on every item in an array and it can return anything. It can have something to do in the current item’s value either do a mathematical equation or concatenation.
  • Filter has a condition and only the items on which the condition returns true will be pushed to a new set of array.
  • Reduce has an accumulator and a current value and you can do something with these two parameters like add them together to combine all the values in the array which then results to a one big single value.
  • Find and findIndex is both used to find the first element that matches a condition.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
chcepe

chcepe

Global citizen, travel junkie, digital ninja, software engineer. chcepe.github.io