Rachel Cole

Rachel Cole

1577347246

JavaScript Map, Reduce, and Filter: What, Why and How to use it

JavaScript Map, Reduce, and Filter - Explained with Examples

Map, reduce, and filter are all array methods in JavaScript. Each one will iterate over an array and perform a transformation or computation. Each will return a new array based on the result of the function. In this article, you will learn why and how to use each one.

Here is a fun summary by Steven Luscher:

Map/filter/reduce in a tweet:

map([๐ŸŒฝ, ๐Ÿฎ, ๐Ÿ”], cook)
=> [๐Ÿฟ, ๐Ÿ”, ๐Ÿณ]

filter([๐Ÿฟ, ๐Ÿ”, ๐Ÿณ], isVegetarian)
=> [๐Ÿฟ, ๐Ÿณ]

reduce([๐Ÿฟ, ๐Ÿณ], eat)
=> ๐Ÿ’ฉ

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.

Syntax

var new_array = arr.map(function callback(element, index, array) {
    // Return value for new_array
}[, thisArg])

In the callback, only the array element is required. Usually some action is performed on the value and then a new value is returned.

Example

In the following example, each number in an array is doubled.

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

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.

Syntax

var new_array = arr.filter(function callback(element, index, array) {
    // Return true or false
}[, thisArg])

The syntax for filter is similar to map, except the callback function should return true to keep the element, or false otherwise. In the callback, only the element is required.

Examples

In the following example, odd numbers are โ€œfilteredโ€ out, leaving only even numbers.

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

In the next example, filter() is used to get all the students whose grades are greater than or equal to 90.

const students = [
  { name: 'Quincy', grade: 96 },
  { name: 'Jason', grade: 84 },
  { name: 'Alexis', grade: 100 },
  { name: 'Sam', grade: 65 },
  { name: 'Katie', grade: 90 }
];

const studentGrades = students.filter(student => student.grade >= 90);
return studentGrades; // [ { name: 'Quincy', grade: 96 }, { name: 'Alexis', grade: 100 }, { name: 'Katie', grade: 90 } ]

Reduce

The reduce() method reduces an array of values down to just one value. To get the output value, it runs a reducer function on each element of the array.

Syntax

arr.reduce(callback[, initialValue])

The callback argument is a function that will be called once for every item in the array. This function takes four arguments, but often only the first two are used.

  • accumulator - the returned value of the previous iteration
  • currentValue - the current item in the array
  • index - the index of the current item
  • array - the original array on which reduce was called
  • The initialValue argument is optional. If provided, it will be used as the initial accumulator value in the first call to the callback function.

Examples

The following example adds every number together in an array of numbers.

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce(function (result, item) {
  return result + item;
}, 0);
console.log(sum); // 10

In the next example, reduce() is used to transform an array of strings into a single object that shows how many times each string appears in the array. Notice this call to reduce passes an empty object {} as the initialValue parameter. This will be used as the initial value of the accumulator (the first argument) passed to the callback function.

var pets = ['dog', 'chicken', 'cat', 'dog', 'chicken', 'chicken', 'rabbit'];

var petCounts = pets.reduce(function(obj, pet){
    if (!obj[pet]) {
        obj[pet] = 1;
    } else {
        obj[pet]++;
    }
    return obj;
}, {});

console.log(petCounts); 

/*
Output:
 { 
    dog: 2, 
    chicken: 3, 
    cat: 1, 
    rabbit: 1 
 }
 */

#JavaScript #WebDev #javascript

What is GEEK

Buddha Community

JavaScript Map, Reduce, and Filter: What, Why and How to use it
Coy  Roberts

Coy Roberts

1600510680

Definitive Guide to Understand Javascript Array reduce()

Javascript array reduce() is an inbuilt method that is used to apply a function to each element in the array to reduce the array to a single value. The reduce() function executes the provided function for each value of an array from left-to-right. The return value of a function is stored in an accumulator.

Understanding Javascript array reduce()

JavaScript array reduce() is one of the pioneer function of functional programming. The reduce() method accepts two parameters, the total and the current value. If you want to add all the values of an array, then use the array reduce() function.

It is similar to both  Javascript map() and  Javascript filter() but, it differs in the callback arguments.

The callback now receives an accumulator (it accumulates all the return values. Its value is the accumulation of a previously returned accumulations), a current value, a current index, and finally, the whole array.

#javascript #javascript map #javascript filter #javascript array reduce

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

**_map, filter and reduce _**are essentially just some of the most well-known, easy to use, higher-order functions that run provided callback on each element of an array.

In this article, we will explore how using map(), filter(), and reduce() can help make our code:

**1.**Easy to comprehend.

2. Less prone to side effects as these function donโ€™t modify the actual array, and instead create a new one.

**3. **Avoid explicit loops.

Letโ€™s explore and familiarize ourselves with these functions.

#functional-programming #filters #maps #javascript #reduce

Coy  Roberts

Coy Roberts

1600868220

Array Foreach, Map, Filter, Reduce, Concat Methods in Javascript

In this tutorial, we will see Javascript Array Foreach, Map, Filter, Reduce, Concat Methods. I dedicate this article only for these methods because, in Pure Functional Programming, this kind of method is required to perform some operations on an Array.

If you do not know What Pure Functions is, then check out my Pure Functions in Javascript article on this website.

Arrays

All the programming languages have this kind of Data Structure to hold and manipulate the data and Javascript is not different.

We all know Arrayscollection of variables, and we all have used to perform some operations like Creating an array, Removing an Item from an Array, Sorting the data of an Array and other manipulations.

In Functional Programming, we are using functions like foreach, map, filter, reduce, concatAll and other Higher Order Functions. So today I am describing these functions in deep and show you how you can use it in various scenarios.

#javascript #programming #foreach #map #filter #reduce

CSS Boss

CSS Boss

1606912089

How to create a calculator using javascript - Pure JS tutorials |Web Tutorials

In this video I will tell you How to create a calculator using javascript very easily.

#how to build a simple calculator in javascript #how to create simple calculator using javascript #javascript calculator tutorial #javascript birthday calculator #calculator using javascript and html

Rachel Cole

Rachel Cole

1577347246

JavaScript Map, Reduce, and Filter: What, Why and How to use it

JavaScript Map, Reduce, and Filter - Explained with Examples

Map, reduce, and filter are all array methods in JavaScript. Each one will iterate over an array and perform a transformation or computation. Each will return a new array based on the result of the function. In this article, you will learn why and how to use each one.

Here is a fun summary by Steven Luscher:

Map/filter/reduce in a tweet:

map([๐ŸŒฝ, ๐Ÿฎ, ๐Ÿ”], cook)
=> [๐Ÿฟ, ๐Ÿ”, ๐Ÿณ]

filter([๐Ÿฟ, ๐Ÿ”, ๐Ÿณ], isVegetarian)
=> [๐Ÿฟ, ๐Ÿณ]

reduce([๐Ÿฟ, ๐Ÿณ], eat)
=> ๐Ÿ’ฉ

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.

Syntax

var new_array = arr.map(function callback(element, index, array) {
    // Return value for new_array
}[, thisArg])

In the callback, only the array element is required. Usually some action is performed on the value and then a new value is returned.

Example

In the following example, each number in an array is doubled.

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

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.

Syntax

var new_array = arr.filter(function callback(element, index, array) {
    // Return true or false
}[, thisArg])

The syntax for filter is similar to map, except the callback function should return true to keep the element, or false otherwise. In the callback, only the element is required.

Examples

In the following example, odd numbers are โ€œfilteredโ€ out, leaving only even numbers.

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

In the next example, filter() is used to get all the students whose grades are greater than or equal to 90.

const students = [
  { name: 'Quincy', grade: 96 },
  { name: 'Jason', grade: 84 },
  { name: 'Alexis', grade: 100 },
  { name: 'Sam', grade: 65 },
  { name: 'Katie', grade: 90 }
];

const studentGrades = students.filter(student => student.grade >= 90);
return studentGrades; // [ { name: 'Quincy', grade: 96 }, { name: 'Alexis', grade: 100 }, { name: 'Katie', grade: 90 } ]

Reduce

The reduce() method reduces an array of values down to just one value. To get the output value, it runs a reducer function on each element of the array.

Syntax

arr.reduce(callback[, initialValue])

The callback argument is a function that will be called once for every item in the array. This function takes four arguments, but often only the first two are used.

  • accumulator - the returned value of the previous iteration
  • currentValue - the current item in the array
  • index - the index of the current item
  • array - the original array on which reduce was called
  • The initialValue argument is optional. If provided, it will be used as the initial accumulator value in the first call to the callback function.

Examples

The following example adds every number together in an array of numbers.

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce(function (result, item) {
  return result + item;
}, 0);
console.log(sum); // 10

In the next example, reduce() is used to transform an array of strings into a single object that shows how many times each string appears in the array. Notice this call to reduce passes an empty object {} as the initialValue parameter. This will be used as the initial value of the accumulator (the first argument) passed to the callback function.

var pets = ['dog', 'chicken', 'cat', 'dog', 'chicken', 'chicken', 'rabbit'];

var petCounts = pets.reduce(function(obj, pet){
    if (!obj[pet]) {
        obj[pet] = 1;
    } else {
        obj[pet]++;
    }
    return obj;
}, {});

console.log(petCounts); 

/*
Output:
 { 
    dog: 2, 
    chicken: 3, 
    cat: 1, 
    rabbit: 1 
 }
 */

#JavaScript #WebDev #javascript