Filter & Map

Map method returns an array, and the same is true for the filter method. This is commonly called chaining methods.

Example

Filter only the odd numbers out of an array of numbers, then convert the new array to an even numbers-only array.

const numbers = [1,2,3,4,5,6,7,8,9,10,11];
const evenNumbers = numbers
  .filter( num => num % 2 !== 0 )
  .map( oddNum => oddNum - 1 );
  
console.log(evenNumbers);
// Output: [0,2,4,6,8,10]
Example

Using the filter and map methods on the years array, create an array of display strings for each year in the 21st century (remember: the 21st century starts with the year “2001”). Each display string should be the year followed by “A.D.” See the comments below to see the correct result. Store the new array in the variable displayYears.

const years = [1989, 2015, 2000, 1999, 2013, 1973, 2012];
let displayYears;

displayYears = years
   .filter( year21 => year21 > 2000 )
   .map( yearStr => yearStr = `${yearStr} A.D.` );

// displayYears should be: ["2015 A.D.", "2013 A.D.", "2012 A.D."]
Example

Using the filter and map methods on the todos array, create an array of unfinished task strings. See the comments below to see the correct result. Store the new array in the variable unfinishedTasks.

const todos = [
    { todo: 'Buy apples', done: false },
    { todo: 'Wash car', done: true },
    { todo: 'Write web app', done: false },
    { todo: 'Read MDN page on JavaScript arrays', done: true },
    { todo: 'Call mom',done: false }
];
let unfinishedTasks;

unfinishedTasks = todos
  .filter( task => task.done === false )
  .map( item => item = item.todo );

// unfinishedTasks should be: ["Buy apples", "Write web app", "Call mom"]

Filter & Reduce

Example

Given the array of objects below:

 const products = [
  { name: 'hard drive', price: 59.99 },
  { name: 'lighbulbs', price: 2.59 },
  { name: 'paper towels', price: 6.99 },
  { name: 'flatscreen monitor', price: 159.99 },
  { name: 'cable ties', price: 19.99 },
  { name: 'ballpoint pens', price: 4.49 }
];

return the product with the heighest price under 10 dollars

const product = products
  .filter( product => product.price < 10 )
  .reduce((highest, product) => {
    if (highest.price > product.price) {
      return highest;
    }
    return product;
  });

console.log(product);    // Result: { name: 'paper towels', price: 6.99 }

The accumulator of reduce() doesn’t have to be used to add or combine elements.

Now, return the total of all products over $10

const total = products
  .filter( product => product.price > 10 )
  .reduce((sum, product) => sum + product.price, 0 )
  .toFixed(2);

console.log(total);    // Result: 239.97