I want to make a new array by adding an element to an existing array by "push()" method.
This is the existing array:
let arr = [{label: 1, value: 1}, {label: 2, value: 2}];
This is the element I want to add to the existing array:
{label: 3, value: 3}
So this is the full code with "push()" method:
let arr = [{label: 1, value: 1}, {label: 2, value: 2}];
let newArr = arr.push({label: 3, value: 3});
console.log(newArr); // 3
But push() method returns the length of the new array which is "3" to "newArr" variable. However, what I really want is the actual new array instead of its length for "newArr" variable.
Are there any ways to get the actual new array for "newArr" variable?
With push you are actually mutating the original array. Immutable array extending is only available in ES2015+ (supported by all current, major browsers). You can use the spread operator ...:
const original = [1, 2];
const next = [...original, 3];
console.log(next); // [1, 2, 3]
Also new is a reserved keyword and can't be used as an identifier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With