Array.push() with Objects - javascript

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

Related

Pushing simple value into an array on the fly

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().

Chain function on array.flat() not working

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

Node.js - Pushing to an array inline

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

What does empty array.slice(0).push(anything) mean?

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);

JQuery - Push method JSONArray

I'm doing the push method between two Arrays to create a bigger Array. The two simple arrays I want to fix are:
[{"id":"11"},{"color":"blue","value":"14"}]
[{"id":"11"},{"color":"green","value":"25"}]
The code to push the two arrays is:
var totjunt = $('body').data('cesta_list').push(array_of_bought_colors_new);
With $('body').data('cesta_list'); I save the first array and then i try to push the second array.
Using console.log(JSON.stringify(totjunt)); I print the value throught the console but the problem is that the console prints only a number 2.
You're logging the result of the push() call, not the resulting array. Try this:
$('body').data('cesta_list').push(array_of_bought_colors_new);
var totjunt = $('body').data('cesta_list');
More specifically, push() returns the length of the new array, not the array itself.
.push doesn't return a new array. It returns the array's new length. The array is updated in-place.

Categories

Resources