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?
First of all, the new
keyword has a specified role in javascript, you can't use it as a variable name.
Reserved keywords in javascript.
Secondly, push
method works in situ, you don't have to assign it to a new variable. It won't return a new array, but modify the original one.
var arr = [{label: 1, value: 1}, {label:2, value:2}];
arr.push({label:3, value:3});
console.log(arr);