Pushing simple value into an array on the fly - javascript

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

Related

JSON.parse returns an array, but cannot be used as an array

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.

Javascript slice isn't giving me correct array length values

Why does it say length 1 instead of 4?
The following is what I'm trying to push and slice. I try and append items.image_urls and slice them into 5 each.
items.image_urls is my dictionary array.
var final_push = []
final_push.push(items.image_urls.splice(0,5))
console.log(final_push.length)## gives me 1...?
var index = 0
final_push.forEach(function(results){
index++ ##this gives me one. I would need 1,2,3,4,5,1,2,3,4,5. Somehting along that.
}
items.image_urls looks like this:
It's an iteration of arrays with image urls.
In your example items.image_urls.splice(0,5) returns an array of items removed from items.image_urls. When you call final_push.push(items.image_urls.splice(0,5));, this whole array is pushed as one item to the final_push array, so it now looks like [["url1", "url2", "url3", "url4", "url5"]] (2-dimensional array). You can access this whole array by calling final_push[some_index].
But what you want instead is to add every element of items.image_urls.splice(0,5) to the final_push. You can use a spread operator to achieve this:
final_push.push(...items.image_urls.splice(0,5));
Spread syntax allows an iterable such as an array expression or string
to be expanded in places where zero or more arguments (for function
calls) or elements (for array literals) are expected
This is exactly our case, because push() expects one or more arguments:
arr.push(element1[, ...[, elementN]])
And here is an example:
let items = {
image_urls: ["url1", "url2", "url3", "url4", "url5", "url6", "url7", "url8", "url9", "url10"]
};
let final_push = [];
final_push.push(...items.image_urls.splice(0,5));
console.log(final_push.length);
console.log(JSON.stringify(final_push));
console.log(JSON.stringify(items.image_urls));
Note: do not confuse Array.prototype.slice() with Array.prototype.splice() - the first one returns a shallow copy of a portion of an array into a new array object while the second changes the contents of an array by removing existing elements and/or adding new elements and returns an array containing the deleted elements.
That seems to be a nested array. So if you would access index 0, and then work on that array like below it will probably work:
console.log(final_push[0].length); //should print 4
The author is mixing up splice and slice. Probably a typo :)
You start at the beginning (0) and then delete 5 items.

Array.push() with Objects

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

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