Skip to content
NH

Nedim Hairlahovic

1 article

April 9, 2020

Map, Filter & Reduce functions in JavaScript

Software Development

Map, Filter & Reduce functions in JavaScript

Map, Filter & Reduce functions in JavaScript Map, filter and reduce functions were introduced in ES6. All of these functions transform an initial list (array) into something else, while keeping the original list intact. We can always use a for loop to get the desired result, but it can be much easier to use these methods and the code will stay cleaner and easier to read. Map Function The map() function creates a new array by calling a specific function on each element in an initial array. In the following example, each number in an array is doubled: With for loop: With map() function: let numbers = [1, 2, 3, 4]; let doubled = []; for (let i = 0; i < numbers.length; i++) {      doubled.push(numbers[i] * 2): } let numbers = [1, 2, 3, 4]; let doubled = numbers.map(num => num * 2);    Filter Function The filter() function creates a new array with elements from the initial array that pass a certain test. For example, the filter() function can be used to create a new array of only positive values: With for loop: With filter() function: let numbers = [1, -2, 3, -4]; let positive = []; for (let i = 0; i < numbers.length; i++) {      if (numbers[i] > 0) {          positive.push(numbers[i]);      } } let numbers = [1, -2, 3, -4]; let positive = numbers.filter(num => num > 0);    Reduce Function The reduce() function applies a specific function to all elements in an array and reduces it to a single value. Here is an example of summing up each number value in an array: With for loop: With reduce() function: let numbers = [1, 2, 3, 4]; let total = 0; for (let i = 0; i < numbers.length; i++) {      total += numbers[i]; } let numbers = [1, 2, 3, 4]; let total = numbers.reduce((total, num) => total + num);    "Map, Filter & Reduce functions in JavaScript" Tech Bite was brought to you by Nedim Hairlahović, Junior Software Engineer at Atlantbh.  (more…)

Ready to Achieve More?

We’ll help you reach your goals quickly with an easy and straightforward process to kick off our collaboration. Here’s what happens next.

STEP 1

Discovery Call

Let’s chat to understand your company, project needs, and answer any questions along the way.

STEP 2

Free Consultation

Work closely with our experts to explore the right solutions for your business.

STEP 3

Collaboration Proposal

We'll recommend the best strategy for your goals, ensuring you get the most from our expertise.

STEP 4

30-Day Cancellation
Policy Contract

Spoiler: It’s Never Been Used

Enjoy peace of mind while we deliver excellence from day one—our track record speaks for itself.

Services you're interested in (Optional)