How to Change the Value of an Array Elements in JavaScript?
Last Updated :
19 Nov, 2024
We can use the Square Bracket Notation to access the value at the given index and change the value by assigning a new value to it. Arrays in JavaScript are mutable, meaning you can modify their elements after they are created. We will explore all the approaches that can be used to access and change the value of a specific index.
1. Accessing Index
To change the value of an array element in JavaScript, simply access the element you want to change by its index and assign a new value to it.
Syntax
colors[1] = "yellow";
JavaScript
// Using direct assignment to change an array element
let colors = ["red", "green", "blue"];
colors[1] = "yellow";
console.log(colors);
Output[ 'red', 'yellow', 'blue' ]
2. Using Array.splice() Method
This approach is going to use Array.splice() method that is used to add the element at a specific position or index.
Syntax
Array.splice(start_index, delete_count, value1, value2, value3, ...)
JavaScript
// Using array methods to change elements
let fruits = ["apple", "banana", "cherry"];
fruits.splice(1, 1, "orange");
console.log(fruits);
Output[ 'apple', 'orange', 'cherry' ]
3. Using fill() Method
The fill() method in javascript is used to change the content of original array at specific index. It takes three parameter (element,startidx,endidx)
Syntax
let arr= [ ]
// startIndex(inclusive) and endIndex(exclusive)
arr.fill (element ,startIndex,endIndex);
console.log(arr);
JavaScript
let arr= ["HTML" , "REACT" , "JAVASCRIPT" , "NODEJS"];
arr.fill("MONGODB",3,4 )
console.log(arr);
Output[ 'HTML', 'REACT', 'JAVASCRIPT', 'MONGODB' ]
4. Using map() Method
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array. It's particularly useful when you want to transform each element of the array.
Syntax
let newArray = array.map(callback(currentValue[, index[, array]])
JavaScript
let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled);
5. Using forEach() Method
The forEach() method executes a provided function once for each array element. This method is useful when you want to iterate over an array and change elements based on a specific condition. Unlike map(), which returns a new array, forEach() modifies the original array.
JavaScript
let numbers = [1, 2, 3, 4, 5, 6];
// Change all even numbers to their double
numbers.forEach((element, index, array) => {
if (element % 2 === 0) {
array[index] = element * 2;
}
});
console.log(numbers);
Output[ 1, 4, 3, 8, 5, 12 ]
6. Using findIndex() Method
In this approach, we use the findIndex method to locate the index of an element that meets a specific condition and then change its value. The findIndex() method returns the index of the first element that satisfies the provided testing function, allowing us to directly access and modify the element.
JavaScript
let numbers = [1, 2, 3, 4, 5];
function updateElement(arr, conditionFn, newValue) {
let index = arr.findIndex(conditionFn);
if (index !== -1) {
arr[index] = newValue;
}
}
let conditionFn = (element) => element === 3;
updateElement(numbers, conditionFn, 10);
console.log(numbers);
Similar Reads
JavaScript - Access Elements in JS Array These are the following ways to Access Elements in an Array:1. Using Square Bracket NotationWe can access elements in an array by using their index, where the index starts from 0 for the first element. We can access using the bracket notation.JavaScriptconst a = [10, 20, 30, 40, 50]; const v = a[3];
2 min read
JavaScript Program for Left Rotate by One in an Array In this article, we are going to learn about left Rotation by One in an Array by using JavaScript, Left rotation by one in an array means shifting all elements from one position to the left, with the last element moving to the first position. The order of elements is cyclically rotated while maintai
5 min read
JavaScript Program to Update the Value for a Specific Key in Map In this article, we will see different approaches to update the value for a specific key in Map in JavaScript. JavaScript Map is a collection of key-value pairs. We have different methods to access a specific key in JavaScript Map. Methods to update the value for a specific key in Map in JavaScriptT
3 min read
JavaScript Program to Swap Characters in a String In this article, We'll explore different approaches, understand the underlying concepts of how to manipulate strings in JavaScript, and perform character swaps efficiently. There are different approaches for swapping characters in a String in JavaScript: Table of Content Using Array ManipulationUsin
6 min read
How to Get the Size of an Array in JavaScript To get the size (or length) of an array in JavaScript, we can use array.length property. The size of array refers to the number of elements present in that array. Syntaxconst a = [ 10, 20, 30, 40, 50 ] let s = a.length; // s => 5 The JavaScript Array Length returns an unsigned integer value that
2 min read
How to Compute the Sum and Average of Elements in an Array in JavaScript? Computing the sum and average of elements in an array involves iterating through the array, accumulating the sum of its elements, and then dividing the sum by the total number of elements to get the average. This can be achieved using various techniques, from basic loops to more advanced functional
3 min read
How to compute the average of an array after mapping each element to a value in JavaScript ? Given an array, the task is to compute the average of an array after mapping each element to a value. Input : arr=[2, 3, 5, 6, 7] Output: 4.6 Explanation : (2+3+5+6+7)/5 = 4.6 Input : [5,7,2,7,8,3,9,3] Output: 5.5 Explanation : (5+7+2+7+8+3+9+3)/8 = 5.5 Here are some common approaches: Table of Cont
3 min read
How to Change Values in an Array when Doing foreach Loop in JavaScript ? The forEach() method in JavaScript is a popular way to iterate through an array. Unlike other looping methods, forEach() passes a callback function for each element in the array. While forEach() itself does not directly change the array, you can modify elements within the array by using the callback
3 min read
How to fill static values in an array in JavaScript ? In this article, we will see the methods to fill an array with some static values. There are many ways to fill static values in an array in JavaScript such as: Using Array fill() MethodUsing for loopUsing push() methodUsing from() methodUsing spread operatorMethod 1: Array fill() Method We use the a
5 min read
How to Empty an Array in JavaScript? To empty an array in JavaScript, we can use the array literal. We can directly assign an empty array literal to the variable, it will automatically remove all the elements and make the array empty.1. Empty Array using Array LiteralWe can empty the array using the empty array literal syntax. Syntaxar
2 min read