JavaScript Array Methods – map, filter, reduce

⏱︎

Read time:

1–2 minutes
js_arrays

Introduction

JavaScript array methods like map(), filter(), and reduce() are essential tools for every developer. They allow you to process and transform arrays in a clean, functional style without mutating the original data.

Array.map() – Transform Each Element

const numbers = [1, 2, 3, 4, 5];

const doubled = numbers.map(n => n * 2);

console.log(doubled); // [2, 4, 6, 8, 10]

// Practical: extract names from objects

const users = [{name: ‘Alice’, age: 25}, {name: ‘Bob’, age: 30}];

const names = users.map(user => user.name);

console.log(names); // [‘Alice’, ‘Bob’]

Array.filter() – Keep Matching Elements

const numbers = [1, 2, 3, 4, 5, 6];

const evens = numbers.filter(n => n % 2 === 0);

console.log(evens); // [2, 4, 6]

// Filter active users

const users = [{name:’Alice’, active:true},{name:’Bob’,active:false}];

const active = users.filter(u => u.active);

console.log(active); // [{name:’Alice’, active:true}]

Array.reduce() – Reduce to a Single Value

const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce((acc, curr) => acc + curr, 0);

console.log(sum); // 15

// Count occurrences

const fruits = [‘apple’,’banana’,’apple’,’orange’,’banana’,’apple’];

const count = fruits.reduce((acc, fruit) => {

  acc[fruit] = (acc[fruit] || 0) + 1;

  return acc;

}, {});

console.log(count); // {apple:3, banana:2, orange:1}

Chaining Methods

const products = [

  {name:’Laptop’, price:999, inStock:true},

  {name:’Phone’, price:499, inStock:false},

  {name:’Tablet’, price:299, inStock:true}

];

// Get total price of in-stock items

const total = products

  .filter(p => p.inStock)

  .map(p => p.price)

  .reduce((sum, price) => sum + price, 0);

console.log(total); // 1298

Conclusion

This guide covered “JavaScript Array Methods – map, filter, reduce with Examples”. Bookmark this page and keep it as your go-to reference. If you found this helpful, share it with fellow developers and check out more snippets on programsnippet.com!

Leave a Reply

Your email address will not be published. Required fields are marked *

Exit mobile version