Node.js - Pushing to an array inline - javascript

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

Related

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

Using array.prototype.fill instead of array.prototype.push

I am trying to use the following prototype to fill an empty array with integers from 1-100. As per MDN's documentation:
array.prototype.fill(value, [optional start & end index])
If my understanding is correct if I call my value = 1 then if I say:
[5].fill(1); I would be left with an array with 1 sitting at all 5 index points of the array. Is there a way using .fill() to say value = 1...100? I'm beginning to think running a for loop to push values 1 - 100 might be the only way to do this, but I thought I would see if this method worked the same.
No, fill method, doesn't take a function or an iterator as an argument to change the static value with every iteration.
try this approach
var N = 100;
var arr = Array.apply(null, {length: N+1}).map(Number.call, Number);
arr.splice(0,1);
console.log(arr);
splice at the end removes the first item of the array which was 0.
If you don't want to do splice
var N = 100;
var arr = Array.apply(null, {length: N}).map(Number.call, function(item, index){ return item + 1 });
console.log(arr);
Some other good approaches are mentioned in this answer to fill values dynamically.
The fill() method fills all the elements of an array from a start index to an end index with a static value.
Therefore, it will not be possible to increment this value using the fill() method.

when push an element in sized array the array size is dynamically grow why?

i'm trying to push a string elements to sized array but when pushing an element the sized array start insert the elements in the last index of the array and grow but i want to insert the first element in the index [0] and second on [1] and so on till index [3] but i don't know why it start to insert elements after the last index and grow when add more element my code :
var users = new Array(3);
users.push(someData);
console.log(users);
console.log(users.length)
and the result like this:
[ , , , 'd', 'dd' ]
5
Avoid using new Array(count). Just create an empty array and then push to it like that:
var users = [];
users.push(someData);
Or, if you have some initial static content, this will be better:
var users = [ someData ];
The reason why I advise you to avoid new Array(...) is because it can be confusing and error-prone:
new Array(3) will create an array with 3 items: [undefined, undefined, undefined].
new Array(3, 4) will create an array containing the items 3 and 4: [3, 4].
Push adds a new element to the end of the array. You create the array with three empty entries then push somethign onto the end. Javascript does not have limited sized arrays. In your case I would guess you want to create an empty arraya nd just push onto it.
The argument you pass to the new Array call sets the initial size, not the maximum size. There is no max size. Just create the array like this:
var users = new Array()
or
var users = []
When you create an array with the constructor and specify a size, that will only set the current length of the array, it won't limit the size of the array.
Doing this:
var users = new Array(3);
does exactly the same thing as this:
var users = new Array();
users.length = 3;
Growing the array by setting the length doesn't actually put anything in the array, it will only set the length property.
The push method looks at the length property when it adds an item, so doing this:
users.push(someData);
does exactly the same thing as:
users[users.length] = someData;
If you want your array to be empty from the start, just create it without setting the length:
var users = new Array();
You can also use the array literal syntax to create an empty array:
var users = [];
Arrays doesn't support limiting the size, so if you want a collection with a limited size, you have to create it yourself (or find one that someone else has created).
array.push() method of array insert element from last index of array. use array.unshift() method to push from starting index of array
Because in javascript "var users = new Array(3);" means creation of array with 3 undefined elements.
For basic Array initialization details you can refer to : http://www.w3schools.com/js/js_arrays.asp

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

How do array sizes work in Javascript

In JavaScript, if you set an array to be of size 5 ( var foo = new Array(5); ), is this just an initial size? Can you expand the number of elements after it is created. Is it possible to do something like this as well - arr = new Array() and then just assign elements one by one? Thanks in advance :-)
Yes it is just an initial size, and it is not required. If you don't use a single number, you can immediately populate.
It is also more common to use the simpler [] syntax.
var arr = ['something', 34, 'hello'];
You can set (or replace) a specific index by using brackets:
arr[0] = "I'm here replacing whatever your first item was";
You can add to the end by using push:
arr.push('add me');
There may be faster performance in some browsers if you do it like this instead:
arr[arr.length] = 'add me';
You can add something at any index.
You can remove an item completely using splice:
arr.splice(0, 1); // remove first item in the array (start at index 0, with 1 being removed)
When you give a new array an explicit size in javascript (using new Array(5)), you populate each index with value of undefined. It is generally considered better practice to instantiate using the array literal [] expression:
var arr = [];
Then, you can push new elements using push()
var arr = [];
arr.push('first value'):
arr.push('second value'):
Check out the MDC Array documentation for more info: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array
Theres a few ways to declare and put values in an array.
First like what you want to do,
var myarr = new Array();
myarr[0] = 'element1';
myarr[1] = 'element2';
myarr[2] = 'element3';
Second way is to define them
var myarr =new Array("element1","element2","element3");
and third is similar to the second
var myarr =["element1","element2","element3"];
You can also check out https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array for a little more information about using the arrays as well. You could use push and pop if you wanted to as well.
If you use jquery or mootools they also have built-in functions to perform on arrays,
http://api.jquery.com/jQuery.each/ for instance.
Have a look at http://www.w3schools.com/js/js_obj_array.asp
var myCars=new Array(); // regular array (add an optional integer
myCars[0]="Saab"; // argument to control array's size)
myCars[1]="Volvo";
myCars[2]="BMW";
Check the documentation for Array, but the simple answer to your question is yes.
var arr5 = new Array(1, 2, 3, 4, 5); // an array with initial 5 elements
var arr = new Array(); // an array without initial
You can also use array literals:
var arr5 = [1, 2, 3, 4, 5];
var arr = [];
Arrays are dynamic in JavaScript. You don't have to initialize them with a certain length. In fact you should use the literal notation [] because of the Array constructor's ambiguity:
If you pass only one parameter to Array, it will set the array length to this parameter. If you pass more than one parameter, these elements are added to the array.
How is the size of the array determined?
The size of an array is the highest index + 1. This can be quite confusing. Consider this:
var arr = [];
arr[41] = 'The answer?';
console.log(arr); // [undefined, undefined, ..., 'The answer?']
console.log(arr.length) // 42
You can even set the length yourself by assigning a number to .length:
arr.length = 99;
If you now add a new element using arr.push(), it will get the index 100 and the length will increase. Whenever you add an element to the array via an index, it is tested whether arr.length is smaller than the index and updated accordingly. But it does not get smaller.
So in fact what var arr = new Array(5) is doing is setting the length of the array to 5. Nothing else.
For more information about creating and populating arrays, I suggest to read about it in the MDC JavaScript Guide.

Categories

Resources