How to replace an item from an array in JavaScript? - GeeksforGeeks

26 Jul, 2021
An item can be replaced in an array using two approaches:
Method 1: Using splice() methodThe 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:
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 ofApproach:Initialize an array.Select the targetd index with the help of .map and .filter methods.Set the new value at targeted indexSyntax:ele[ele.map((x, i) => [i, x]).filter(x => x[1] == old_value)[0][0]] = new_valueExample 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:
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:
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
javascript-array
JavaScript-Misc
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?