An item can be replaced in an array using two approaches:
- Method 1: Using splice() method
The array type in JavaScript provides us with splice() method that helps us in order to replace the items of an existing array by removing and inserting new elements at the required/desired index.
Approach:
- Initialize an array and then we applied the splice() method on it resulting the insertion of the element “February” at index 1 without removing any element.
- Apply another splice() method on the resulted array after the first splice(), in order to replace the element “June” which is at index 4 (in the output array of the first splice() method) by the element “May”.
Syntax:
Array.splice(start_index, delete_count, value1, value2, value3, ...)
Note: Splice() method deletes zero or more elements of an array starting with including the start_index element and replaces those elements with zero or more elements specified in the argument list.
Splice() method modifies the array directly dissimilar to the similarly named Slice() method.
Example 1: Below are some examples to illustrates Splice() method:
This example illustrate the simple use of splice method.<!DOCTYPE html>
<html>
<body>
<center>
<h1 style=
"color:green"
>
GeeksforGeeks
</h1>
<p>Click on the button to replace the array elements.
</p>
<button onclick=
"element_replace()"
>
Replace
</button>
<p>The Updated Array Elements:</p>
<p id=
"result"
></p>
<script>
function
element_replace() {
// Initializing the array
var
list = [
"January"
,
"March"
,
"April"
,
"June"
];
// splicing the array elements using splice() method
list.splice(1, 0,
"February"
);
// expected output [January, February, March, April, June]
// splicing the output elements after the first splicing
list.splice(4, 1,
"May"
);
document.getElementById(
"result"
).innerHTML = list;
}
</script>
</center>
</body>
</html>
Output after clicking the button:
- Method 2: Using array map() and filter() methods.
The map() method in JavaScript creates an array by calling a specific function on each element present in the parent array. arr.filter() the function is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument function. With the help of
Approach:
- Initialize an array.
- Select the targetd index with the help of .map and .filter methods.
- Set the new value at targeted index
Syntax:
ele[ele.map((x, i) => [i, x]).filter(x => x[1] == old_value)[0][0]] = new_value
Example 2:
<!DOCTYPE html>
<html>
<body>
<center>
<h1 style=
"color:green"
>
GeeksforGeeks
</h1>
<p>
Click on the button to
replace the array elements.
</p>
<button onclick=
"element_replace()"
>
Replace
</button>
<p>The Updated Array Elements:</p>
<p id=
"result"
></p>
<script>
function
element_replace() {
var
ele = Array(10, 20, 300, 40, 50);
ele[ele.map((x, i) => [i, x]).filter(
x => x[1] == 300)[0][0]] = 30
console.log(ele);
}
</script>
</center>
</body>
</html>
Output: