Tuesday, 26 November 2024

JavaScript's map Method to process Array Elements

The map method in JavaScript is one of the most commonly used methods to work with arrays. It's a powerful tool, especially in React applications, because it helps you create new arrays based on existing ones by applying a transformation to each item.

Syntax

array.map(function(currentValue, index, array), thisArg)

 

1.   currentValue: The current element being processed in the array.

2.   index (optional): The index of the current element being processed.

3.   array (optional): The array map was called upon.

4.   thisArg (optional): Value to use as this when executing the callback.

 

doubleNumbers.js

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

const doubledNumbers = numbers.map(function(number) {
  return number * 2;
});

console.log(`numbers : ${numbers}`);
console.log(`doubledNumbers : ${doubledNumbers}`);

Output

numbers : 1,2,3,4,5
doubledNumbers : 2,4,6,8,10

The map method allows you to use an optional second argument, index, which represents the position of the element in the array. This can be useful if you need to do something with both the value and its index.

 

printWithIndex.js

const fruits = ['Apple', 'Banana', 'Cherry'];

const fruitWithIndex = fruits.map((fruit, index) => {
  return `${index + 1}: ${fruit}`;
});

console.log(`fruits : ${fruits}`);
console.log(`fruitWithIndex : ${fruitWithIndex}`);

Output

fruits : Apple,Banana,Cherry
fruitWithIndex : 1: Apple,2: Banana,3: Cherry

JavaScript map() method returns a new array, and not modifies the original array. The map() method iterates over the elements of an array and applies a function to each element, returning a new array with the results, without changing the original array.


Previous                                                    Next                                                    Home

No comments:

Post a Comment