Wednesday, 15 May 2019

.map(), .reduce(), and .filter() in Javascript

Introduction
 .map(), .reduce(), and .filter() are new features in Javascript. In this article i will tell you example of  .map(), .reduce(), and .filter() function,
Sujeet Bhujbal Javascript





What is .map()

The Map object holds key-value pairs and remembers the original insertion order of the keys.Any value  may be used as either a key or a value.

Map object iterates its elements in insertion order — a for loop returns an array of [key, value] for each iteration.

The map() method creates a new array with the results of calling a function for every array element.
The map() method calls the provided function once for each element in an array, in order

Example : 


If you want ids of all employees There are multiple ways to achieve this. You might want to do it by creating an empty array, then using .forEach().for(...of), or a simple .for() to meet your goal.



var Employees = [
  { id: 20, name: 'Sujeet' },
  { id: 24, name: 'Rahul' },
  { id: 56, name: 'Raj' },
  { id: 88, name: 'ASSHAY' }
];

const empIds = Employees.map(emp => emp.id);

console.log(empIds)

OutPut

(4) [20, 24, 56, 88]



What is .Reduce()

 

The reduce() method reduces the array to a single value. The reduce() method executes a provided function for each value of the array (from left-to-right). The return value of the function is stored in an accumulator (result/total).

The reduce() method reduces the array to a single value.
The reduce() method executes a provided function for each value of the array (from left-to-right).
The return value of the function is stored in an accumulator (result/total).

Example


   var employees = [
  {
    id: 10,
    name: "Sujeet",
    years: 10,
  },
  {
    id: 2,
    name: "Rahul",
    years: 3,
  },
  {
    id: 41,
    name: "Ramesh",
    years: 1,
  },
  {
    id: 99,
    name: "Sumit",
    years: 12,
  }
];

const totalYears = employees.reduce((acc, emp) => acc + emp.years, 0);

console.log(totalYears)

OutPut : 26



Waht is .filter()


if you have an array but want some of the elements in it. You can use .filter() here

   var employees = [

  {
    id: 10,
    name: "Sujeet",
    years: 10,
  },
  {
    id: 2,
    name: "Rahul",
    years: 3,
  },
  {
    id: 41,
    name: "Ramesh",
    years: 1,
  },
  {
    id: 99,
    name: "Sumit",
    years: 12,
  }
];

c      const emp = employees.filter(emps => emps.name === "Sujeet");
        console.log(empDetails)


   OutPut

   
  1. [{…}]
    1. length1




Happy programming!!
Don’t forget to leave your feedback and comments below!


Regards
Sujeet Bhujbal
--------------------------------------------------------------------------------
------------------------------------------------------------------------------



No comments:

Post a Comment