Techoceanhub logo

Array Methods (map, filter, reduce, etc.)

Absolutely, JavaScript provides a rich set of array methods for manipulating and transforming data within arrays. Here’s a breakdown of some commonly used methods with examples:

1. map():

This method creates a new array by applying a function to each element of the original array. It’s useful for transforming elements based on a specific logic.

  • Example: Let’s say you have an array of numbers and want to double each value.
const numbers = [1, 2, 3, 4, 5];

const doubledNumbers = numbers.map(number => number * 2);

console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]

filter():

This method creates a new array containing only elements that pass a test implemented by a provided function.

  • Example: Let’s create a new array with only even numbers from the previous numbers array.
const evenNumbers = numbers.filter(number => number % 2 === 0);

console.log(evenNumbers); // Output: [2, 4]

forEach():

This method executes a provided function once for each element in the array. It doesn’t create a new array, but is useful for performing side effects on each element (e.g., logging).

  • Example: Let’s simply log each number in the numbers array.
numbers.forEach(number => console.log(number));

// Output: 1, 2, 3, 4, 5 (each number on a new line)

These are just a few examples, and there are many other array methods available in JavaScript like find(), findIndex(), sort(), and more.

Share:

Categories

Archives

Related Posts

Array Destructuring

Array Destructuring Array destructuring is a powerful syntax introduced in ES6 that allows you to unpack elements from an array

Read More »

Explore our Affiliated partner links

hostgator website plan

Hostgator

Best Website hosting plans & Best for 24/7 support.

hostinger webhosting plan

Hostinger

Reasonable website hosting packages for small business & 24/7 Email support

Elementor pro

Design Worpdress website quickly using Elementor Builder and AI

buy elementor website templates

Buy Elementor Website Template

Buy ready made Elementor Website Template from us & Get Free Elementor pro licence for 1 year .