- Javascript set value array
- # Table of Contents
- # Update all elements in an array in JavaScript
- # Update all Elements in an Array using Array.map()
- # Update all Elements in an Array using Array.reduce()
- # Modify all Elements in an Array using a for loop
- # Set all Array Elements to a Specific Value using Array.fill()
- # Additional Resources
- Set all array elements to a specific value in JavaScript
- How to set all array elements to a specific value in JavaScript
- Using fill()
- Using forEach()
- Using a for loop
- Summary
Javascript set value array
Last updated: Dec 22, 2022
Reading time · 4 min
# Table of Contents
# Update all elements in an array in JavaScript
To update all elements in an array:
- Use the Array.forEach() method to iterate over the array.
- Use the index of the current iteration to update each element.
Copied!const arr = ['bobby', 'hadz', 'com']; arr.forEach((element, index) => arr[index] = element + index; >); console.log(arr); // 👉️ [ 'bobby0', 'hadz1', 'com2' ]
The function we passed to the Array.forEach method gets called with each element in the array.
The function gets passed 3 arguments on each iteration:
You can use this approach to modify all array elements using any value.
Copied!const arr = [1, 2, 3, 4, 5]; arr.forEach((element, index) => arr[index] = element + 10; >); console.log(arr); // 👉️ [ 11, 12, 13, 14, 15 ]
On each iteration, we access the array element at the current index and update its value by adding 10 to it.
We could have achieved the same result by using a plain for loop. However, for loops are a bit more verbose and indirect.
# Update all Elements in an Array using Array.map()
This is a three-step process:
- Use the Array.map() method to iterate over the array.
- The Array.map() method gives us access to the current element and its index.
- Use the index to modify the value of each element and return the result.
Copied!const arr = ['bobby', 'hadz', 'com']; const newArray = arr.map((element, index) => return element + index; >); // 👇️ [ 'bobby0', 'hadz1', 'com2' ] console.log(newArray);
We used the map() method in a similar way to how we used the forEach() method.
However, this time we don’t change the elements in the original array. Instead, we create a new array containing the modified elements.
The function we passed to Array.map() gets called with each element in the array and its index.
On each iteration, we modify the value of the current element using the index and return the result.
The map() method returns a new array containing the values returned from the callback function.
# Update all Elements in an Array using Array.reduce()
This is a two-step process:
- Use the Array.reduce() method to iterate over the array.
- Update the value of each element and return the accumulated array.
Copied!const arr = ['bobby', 'hadz', 'com']; const newArray = arr.reduce((accumulator, element, index) => return [. accumulator, element + index]; >, []); // 👇️ [ 'bobby0', 'hadz1', 'com2' ] console.log(newArray);
The function we passed to the Array.reduce method gets called for each element in the array.
We initialized the accumulator variable to an empty array because that’s what we passed as the second argument to the reduce() method.
The value we return from the callback function gets passed as the accumulator on the next iteration.
On each iteration, we use the spread syntax (. ) to unpack the values of the array into a new array and add the current element + its index to the end of the array.
The Array.reduce() method returns a new array and doesn’t mutate the original.
# Modify all Elements in an Array using a for loop
This is a two-step process:
- Use a for loop to iterate over the array.
- Use the current index to modify each array element.
Copied!const arr = ['a', 'b', 'c']; for (let index = 0; index arr.length; index++) arr[index] = arr[index] + index; > console.log(arr); // 👉️ ['a0', 'b1', 'c2']
The code sample is similar to the previous one that used the Array.forEach() method.
However, we used a for loop to iterate over the array.
It’s a matter of personal preference but in my opinion the forEach() approach is more readable and intuitive.
Most experienced developers avoid mutating arrays and objects. Instead, they create new arrays containing the desired elements.
We can use the Array.map() or Array.reduce() methods to achieve this.
# Set all Array Elements to a Specific Value using Array.fill()
You can use the fill() method to set the elements on an array to a specific value.
The fill method changes the elements in an array, setting them to a static value and returns the modified array.
Copied!const arr = new Array(3).fill('value'); // 👇️ ['value', 'value', 'value'] console.log(arr);
We called the Array.fill method on an existing array with a set length to fill the array with a specific value.
You can also use an existing array’s length to determine the length of the new array.
Copied!const existingArr = [1, 2, 3]; const newArr = new Array(existingArr.length).fill(100); // 👇️ [100, 100, 100] console.log(newArr);
The argument we passed to the fill() method is the value with which to fill the array.
The Array() constructor creates an array of N empty elements, which we can fill using the fill() method.
Copied!// 👇️ [,,] console.log(new Array(3))
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Set all array elements to a specific value in JavaScript
We will learn how to set all array elements to a specific value in JavaScript using fill() and forEach(). Let’s read this article now.
How to set all array elements to a specific value in JavaScript
Using fill()
The easiest way to set all array elements to a specific value in JavaScript is using the fill() method.
This method will execute a statement for each iteration:
This method works on an array, and it will set all the array elements to a specific value:
let arr = ["LearnShare IT", "Learn Share IT", "Learn ShareIT"]; // Set all array elements to a specific value: "LearnShareIT" arr.fill("LearnShareIT"); console.log(arr);
['LearnShareIT', 'LearnShareIT', 'LearnShareIT']
The above example defined a new array that contains 3 different values. We used the method fill() to set the values of these elements to “LearnShareIT”. If you don’t have an array that already contained the elements. You might want to create a new array with a given size to change all elements’ values. For example:
// Create an array of 3 elements without values let arr = new Array(3); // Set all array elements to a specific value: "LearnShareIT" arr.fill("LearnShareIT"); console.log(arr);
['LearnShareIT', 'LearnShareIT', 'LearnShareIT']
Using forEach()
This method will execute a statement for each iteration:
There are three distinct methods to apply this strategy depending on what genuine values you desire, as was clearly stated in the prior solution:
let arr = ["LearnShare IT", "Learn Share IT", "Learn ShareIT"]; // Set all array elements to a specific value: "LearnShareIT" arr.forEach((value, index) => (arr[index] = "LearnShareIT")); console.log(arr);
['LearnShareIT', 'LearnShareIT', 'LearnShareIT']
As can be seen, this method also produces the same results as the first solution. However, we suggest you use the first solution as it will help you set all array elements if the elements are empty (don’t have values).
Using a for loop
The loop is the most basic control abstraction in any programming language. You can iterate through each element in the array and then assign the element’s value to a value you want:
let arr = ["LearnShare IT", "Learn Share IT", "Learn ShareIT"]; // Set all array elements to a specific value: "LearnShareIT" for (let i = 0; i < arr.length; i++) < arr[i] = "LearnShareIT"; >console.log(arr);
['LearnShareIT', 'LearnShareIT', 'LearnShareIT']
Here is another example of an array with empty values:
let arr = new Array(4); // Set all array elements to a specific value: "LearnShareIT" for (let i = 0; i < arr.length; i++) < arr[i] = "LearnShareIT"; >console.log(arr);
['LearnShareIT', 'LearnShareIT', 'LearnShareIT', 'LearnShareIT']
Summary
We have discovered how to set all array elements to a specific value in JavaScript. We suggest you use the first method of using fill(); however you should read the third one before implementing it. We hope you succeed with our tutorials.
Maybe you are interested:
I’m Edward Anderson. My current job is as a programmer. I’m majoring in information technology and 5 years of programming expertise. Python, C, C++, Javascript, Java, HTML, CSS, and R are my strong suits. Let me know if you have any questions about these programming languages.
Name of the university: HCMUT
Major: CS
Programming Languages: Python, C, C++, Javascript, Java, HTML, CSS, R