I want to clone a new array from an existing one and push in an element.
Unfortunately, the existing array is an empty one, so it's like:
[].slice().push(65)
the output of above expression is 1.
Why is it 1?
Array#push() returns the length of the resultant array. Since you're pushing a single value onto an empty array, the length of the result will indeed be 1.
If you want to see the updated array as output, you'll need to save a reference to it since push() does not return a reference:
var arr = [].slice();
arr.push(65);
console.log(arr); // [ 65 ]
Changing my comment to an answer:
MDN push(): The push() method adds one or more elements to the end of an array and returns the new length of the array.
You need to do it in two steps, not one with that pattern.
var temp = [].slice();
temp.push(65);
console.log(temp);
If you want to do it in one line, look into concat()
var a = [1,2,3];
var b = [].concat(a,64);
console.log(b);
Related
I want to be able to create an array with only one value inside of it on the fly without using a variable. This works with a variable:
var arr = [];
arr.push('test');
console.log(arr); // correctly logs ["test"]
But this does not:
console.log([].push('test')); // logs 1
Why does this log 1 instead of ["test"]? Is this coerced into a boolean?
Array.prototype.push returns the new length of the array, not the pushed item nor the array it-self.
"I want to be able to create an array with only one value inside of it
on the fly without using a variable"
const arr = ['test'];
console.log(['test']);
Array.prototype.push()
The push() method adds one or more elements to the end of an array and returns the new length of the array.
In the first example you are first pushing the element in the array then log the array. But in the second example you are logging the returned result of push().
Why chaining function on array.flat not working as expected
const input = [[[{"type":"banana"},{"type":"orange"}]]];
console.log(input.flat(2).push({"type":"grapes"}));
What I expect is, it should remove the 2 array wrapper and push a new item to input
But I get only the length why is that ?
Array#push returns the new length of the array.
You could concat the array (Array#concat) with a new element and get the new array.
console.log(input.flat(2).concat({ type: "grapes" }));
Array.push mutates the array itself and returns only the length of the array. You can log the array in the next line after the push statement.
The push method returns the new length of the array and mutates it.
Try instead:
const input = [[[{"type":"banana"},{"type":"orange"}]]];
const flattened = input.flat(2)
flattened.push({"type":"grapes"});
console.log(flattened)
/*
[
{type:"banana"},
{type:"orange"},
{type:"grapes"}
]
*/
You can also other than Array.concat also spread into a new array to achieve the same result:
const input = [[[{"type":"banana"},{"type":"orange"}]]];
console.log([...input.flat(2), {"type":"grapes"}]);
The issue in your code however is that Array.flat returns a whole new array for you to work with and Array.push simply returns the new length of the array (so you need to keep a reference to the array). So with some refactoring:
const input = [[[{"type":"banana"},{"type":"orange"}]]];
let newArr = input.flat(2) // <-- this would return a new array
newArr.push({"type":"grapes"}) // We do not care what push returns since we have a reference to the array
console.log(newArr)
You get the expected result
Also note of caution with Array.flatMap and Array.flat ... both do not have support in IE and you would need a polyfill
Consider the following situation:
const JSONString = `["a", "b"]`;
console.log(JSON.parse(JSONString).push("c")); //returns 3 (length)
Why does JSON.parse return the array and allows Array methods on it, but when you actually try to push something in the array it returns the length?
If we do the following it will work:
const JSONString = `["a", "b"]`;
console.log(JSON.parse(JSONString).concat("c"));
Here above is the original question and answered correctly below by Quentin.
Performance question:
Would would be preferable in the situation above: concat or push, where concat is only one line but returns a new array. push needs more lines of code, but keeps the original array?
Why does JSON.parse return the array
Because it is an array
allows Array methods on it
Because it is an array
when you actually try to push something in the array it returns the length?
Because the return value of the push function is the length of the array
To quote MDN:
The push() method adds one or more elements to the end of an array and returns the new length of the array.
JSON.parse is irrelevant to this:
const array = ["a", "b"];
const return_value = array.push("c");
console.log({ array, return_value });
Would would be preferable in the situation above: concat or push, where concat is only one line but returns a new array. push needs more lines of code, but keeps the original array?
If you need the original array then the answer is obvious.
If you don't, then it is a matter of opinion.
Is there any reason why I canot .push() objects into an Array? Simplified example below.
let myArray = [{x:1},{x:2}];
let myObj = {x:1};
let x = myArray.push(myObj);
console.log(x)
// I'am expecting [{x:1},{x:2},{x:1}] but I get 3
The return value of push is the length of the modified array. It isn't another reference to the same array, nor is it a new array.
If you want to log the array, then console.log(myArray) instead of x.
Simple, push just returns the length of the new array and the array was modified in place. Try:
console.log(myArray)
myArray.push(myObj) returns a number of objects it has. you are displaying the array length. If we print myArray you could see the array of Object.
You should console.log(myArray); The way you do returns the new length of the array, which you assign another reference
DEMO
let myArray = [{x:1},{x:2}];
let myObj = {x:1};
console.log(myArray);
myArray.push(myObj);
console.log(myArray);
Array.push() function is working properly, and it returns the new length of the array
The push() method adds one or more elements to the end of an array and returns the new length of the array.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push?v=a
Why are these two values different?
var sliced = [1,2].slice(1);
sliced.push(3);
console.log(sliced);
var sliced = [1,2].slice(1).push(3);
console.log(sliced);
perhaps this can shed light onto why this doesn't work:
var result = process.argv.slice(1).push('xyz');
but this does:
var result = process.argv.slice(1).concat('xyz');
.push returns the new length of the array that the value was pushed to, not the array it was pushing to.
.push method return the length of array it was pushed to. For details take a look here
.push returns as per MDN
The new length property of the object upon which the method was
called.
So even if you take 5, 6 and 7 as array element it will return length of array
var sliced = ([5,6,7].slice(1)).push(3);
console.log(sliced);
Output is 3