'How to update an array everytime when pushing values
I am facing difficulty while pushing the values inside the array.
Suppose I have array like this
const arr = ["tom", "harry", "mike"];
What I want to achieve is, when I am pushing values inside this array. I don't want to append that value in the array, but create a new array with the appended value and not change the old array.
Solution 1:[1]
Push is meant to be modify the array so I think you can take advantage of spread operator to create new array with new value added instead of modifying the old one.
let arr = ["j", "d", "s"];
let newFrontAdd = ["new value", ...arr]
let newRearAdd = [ ...arr, "new value"]
console.log("original array : ", arr);
console.log("added value at front : ", newFrontAdd);
console.log("added value at rear : ", newRearAdd);
Solution 2:[2]
Everything you need to know about arrays is here: https://www.w3schools.com/js/js_arrays.asp
When talking about arrays, the term push
means to append.
const arr = ["tom", "harry", "mike"];
arr.push("swapnil")
// arr: ["tom", "harry", "mike", "swapnil"]
If you want to set a particular index, you may do that like so:
const arr = ["tom", "harry", "mike"];
arr[1] = "swapnil"
// arr: ["tom", "swapnil", "mike"]
If you'd like to overwrite the entire array, you can't use const
. Use let
(or var
) instead.
let arr = ["tom", "harry", "mike"];
arr = ["swapnil", "steve]
// arr: ["swapnil", "steve"]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Steve |