MongoDB Articles

Javascript Map, Filter, Reduce methods

0 👍
👎 0
 MongoDB

Map

The map() method is used for creating a new array from an existing one, applying a function to each one of the elements of the first array.

let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map(num => num * 2);
console.log(doubled) // [2, 4, 6, 8, 5] 

Filter

The filter() method takes each element in an array and it applies a conditional statement against it. If this conditional returns true, the element gets pushed to the output array. If the condition returns false, the element does not get pushed to the output array.

const numbers = [1, 2, 3, 4];
const odds = numbers.filter(num => num % 2 === 1);
console.log(odds); // [1, 3]

Or with an array of Objects you can implement filter() like the following.  

const students = [
{name: 'eric', age: 12},
{name: 'Jenny' age: 11},
{name: 'Freddy', age: 9}
];
const overTen = students.filter(student => student.age > 10); console.log(overTen); // [{name:'Eric', age:12}, {name:'Jenny', age:11}]

Reduce

The reduce() method reduces/calculates a value down to a single value. To get the output value, it runs a reducer function on each element of the array.

const array1 = [1, 2, 3, 4];   // 0 + 1 + 2 + 3 + 4
const initialValue = 10;
const sumWithInitial = array1.reduce(
(accumulator, currentValue) => accumulator + (currentValue * 10), 
initialValue
);

// Expected output is 110.  Ok so the accumulator starts at the value of zero.  And then accumulator is accumulator plus currentValue times 10.  Add 10(initialValue... we set it to 10) + 10 + 20 + 30 + 40

 

Javascript Spread Operator ...

0 👍
👎 0
 MongoDB

The javascript spread operator ... is a convenient way to insert an array into a second array.  Used mainly when defining the array data.  Consider the following:

/****
 * The x array is placed inside of noSpread as a child array inside.
 * noSpread array is now ['u', Array(2), 3, 7]
 ****/
let x = ['a', 2];
let noSpread = ['u', x, 3, 7];

/***
 * using the spread operator ...x
 * the spread array is now ['u', 'a', 2, 5, 6]
 ***/
 
let x = ['a', 2];
let spread = ['u', ...x, 5, 6];