Apply a function to each member of an array in JavaScript
This post will discuss how to apply a function to each member of an array in JavaScript.
There are several ways to apply a function to each member of an array in JavaScript, depending on our preferences and the type of function. Here are some of the possible functions, along with some examples:
1. Using Array.forEach() function
One way to apply a function to each member of an array in JavaScript is to use the Array.forEach() function. This function takes a callback function as an argument and executes it for each element in the array. The callback function can access the current element, its index, and the array itself as parameters. For example, if we have an array of numbers and a function that squares them, we can use the forEach() function to apply the function to each number and print the result:
|
1 2 3 4 5 6 7 8 9 10 11 |
let arr = [1, 2, 3]; let sum = 0; let add = function(x) { sum += x; }; // apply the add function to each element arr.forEach(add); console.log(sum); // 6 |
2. Using Array.map() function
The Array.map() function creates a new array with the results of calling a function on every element in the original array. The function can access the current element, its index, and the array itself as parameters. This function returns the new array, and it does not modify the original array. It is useful for transforming or mapping an array into another array based on a function. Here’s an example:
|
1 2 3 4 5 6 7 8 9 10 |
let arr = [1, 2, 3]; let square = function(x) { return x * x; }; // apply the square function to each element and store the results in a new array let newArr = arr.map(square); console.log(newArr); // [1, 4, 9] |
3. Using a loop
Another option is to iterate over the array and explicitly call the function on each element. We can use any kind of loop, such as a for loop, a while loop, or a for-of loop. Here’s an example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
let arr = [1, 2, 3]; let double = function(x) { return x * 2; }; for (let i = 0; i < arr.length; i++) { // apply the double function to each element arr[i] = double(arr[i]); } console.log(arr); // [2, 4, 6] |
That’s all about applying a function to each member of an array in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)