Map Reduce Filter

Filter is the most basic and useful "high order function", that is we can pass a function to it

Filter

The filter() method creates an array filled with all filtered array elements that pass a test (provided as a function). // returns true or false

var foo = [1,2,'a','b'];
 
function getNumbers(number) {
  return Number.isInteger(number);
}
 
var filterNumbers = foo.filter(getNumbers);
 
console.log(filterNumbers); // 1,2

Map

The map method creates a new array with a mutated value of an array, again passing through a function

var foo = ['Williams','Davis','Carroll','Jones'];
 
function setTitle(value, index) {
  return `Mr ${value}`; 
}
 
var names = foo.map(setTitle);
 
console.log(names); // ['Mr Carroll', 'Mr Davis'].....etc

Reduce

The reduce() method reduces the array to a single value.
You might not realize it, but often in programming you'll need to take a list of things and merge them into just one item.

var foo = [12,67,5,6,7];
 
function getTotal(total, number) { // params are total, value, index
  return total + number; 
}
 
var total = foo.reduce(getTotal,0); // 0 is initial value 
 
console.log(total);
const items = ['cat','cat','dog','dog','mouse'];
 
var reducer = (obj, item)=> {  
  if(!obj[item]) {
    obj[item] = 1;
  } else {
    obj[item] = obj[item] + 1; 
  } 
  return obj;
}
 
var newObj = items.reduce(reducer, {});
 
console.log(newObj);
 
/*
Object {
  cat: 2,
  dog: 2,
  mouse: 1
}
/*

Using just a function expression (Cleaner)

const items = ['cat','cat','dog','dog','mouse'];
var newObj = items.reduce( function(obj, item) {  
  if(!obj[item]) {
    obj[item] = 1;  
  } else {
    obj[item] = obj[item] + 1; 
  } 
  return obj; 
}, {});
 
console.log(newObj);
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License