Javascript: Processing collections with map, reduce, and filter

Map executes that callback on every element within it, returning a new array with all of the values that the callback returned. Map passes three arguments to your callback:

  • The current item in the array
  • The current index
  • The entire array you called map on

Filter takes an array, and filters out unwanted elements.Filter passes your callback three arguments:

  • The current item
  • The current index
  • The array you called filter on

Reduce takes all of the elements in an array, and reduces them into a single value. Reduce passes your callback four arguments:

  • The current value
  • The previous value
  • The current index
  • The array you called reduce on
  •  
     	 
    var isEven = num => num % 2 === 0;
    var square = num => num * num;
    var add = (a, b) => a + b;
      
    var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
      
    arr.filter(isEven).map(square).reduce(add); 
    
    
    Output: 220
    

Read More

How to sort javascript array with objects?


var people = [
    {Name: "Jack Lee", Age: 21},
    {Name: "Jack Ma", Age:31},
    {Name: "Steve Liu", Age: 12},
    {Name: "Alice  Xu", Age: 42}
];


//Sort by name
people.sort(function(a,b){
   return   (a.Name.toLowerCase() > b.Name.toLowerCase()) ? 1 : -1;
});

//Sort by ES6 arrow function
people.sort((a,b)=>{
   return   (a.Name.toLowerCase() > b.Name.toLowerCase()) ? 1 : -1;
});

Sorted array by name:
>people
 
0: {Name: "Alice  Xu", Age: 42}
1: {Name: "Jack Lee", Age: 21}
2: {Name: "Jack Ma", Age: 31}
3: {Name: "Steve Liu", Age: 12} 


//sort by age
 people.sort(function(a,b){
   return   (a.Age > b.Age)? 1 : -1;
});


//Sort by ES6 arrow function
 people.sort((a,b)=>{
   return   (a.Age > b.Age)? 1 : -1;
});

Sorted array by age:
>people

0: {Name: "Steve Liu", Age: 12}
1: {Name: "Jack Lee", Age: 21}
2: {Name: "Jack Ma", Age: 31}
3: {Name: "Alice  Xu", Age: 42} 

Read More