DevClub - JavaScript Map, Reduce, Filter

Table of contents

Featured Program - MAP, REDUCE, FILTER

Click on a guest or attraction to view details.

Lesson 38 - MAP()

Map creates a new array with the results of calling a function for every array element.

Note: The original array is not modified.

Lesson 39 - REDUCE()

Reduce executes a function on each element of the array, resulting in a single output value.

Lesson 40 - FILTER()

Filter creates a new array with elements based on the test implemented in the function.

Lesson 41 - Array Methods

BONUS : Prototyping

When i saw the .reduce() method, i discovered that functions like .sum() from LINQ doesn't exist in JavaScript, but we can create our own using prototypes.

Array.prototype.sum = function() {
    return this.reduce((acc, item) => acc + item, 0);
};

Now we can use the .sum() method on any array of numbers:

const numbers = [1, 2, 3, 4, 5];
const total = numbers.sum(); // total will be 15

Note: This approach modifies the Array prototype, which can have unintended consequences if not used carefully. (can cause conflicts with other code/libraries)

BONUS : Spread Operator

The spread operator (`...`) allows an iterable to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected.

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const combined = [...array1, ...array2]; // [1, 2, 3, 4, 5, 6]

It can also be used to create a shallow copy of an array or to merge objects.

const original = { a: 1, b: 2 };
const copy = { ...original }; // { a: 1, b: 2 }
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const merged = { ...obj1, ...obj2 }; // { a: 1, b: 3, c: 4 }
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
	
const merged = { ...obj1, ...obj2 };
// { a: 1, b: 3, c: 4 }
	
const merged2 = { ...obj2, ...obj1 };
// { b: 2, c: 4, a: 1 }

Note: When merging objects, if there are properties with the same name, the value from the last object will overwrite the previous one.

Project 06 - Final Project