How does it work push empty array into an empty array - javascript

var ar = [];
console.log(ar.push([])); // 1
I expected the log to be [[]], but it show me 1. What is going on above the code.

According to MDN, the Array#push returns:
The new length property of the object upon which the method was called.
So, in your case, as you are pushing an element to an empty array - which makes the length 1 - hence the result.
In case you wish to confirm:
// Empty array.
var arr = [];
// Push an item: result = 1
console.log(arr.push([]));
// Push another item: result = 2
console.log(arr.push([]));

Related

Inserting items into array with bracket syntax doesnt affect length?

An array's length does not increase when adding items with bracket syntax. How do you update the length?
Example:
const a = [];
a['u123'] = 1;
a['u456'] = 2;
a.length; // returns 0
Arrays do not have keys, so your way of accessing them is also wrong. You could instead use push to add values to the array and the values will be index based, not key based.
const a = [];
a.push('u123');
a.push('u456');
console.log(a.length);
Or you could make your data an object instead, to have a key-value pair:
const a = {};
a['u123'] = 1;
a['u456'] = 2;
console.log(Object.keys(a).length)
That's because you are not adding items to the array instead you are inserting entries (key-value pairs) to your object.
You can check the length of the entries using the below syntax:
Object.keys(a).length // returns 2
If you want to add items to the array, use the below syntax:
a.push(1);
a.push('u123')
// ES6 syntax using spread operator
a = [...a, 2, 'u456']
a.length // returns 4
In order to get the length of an associative array you need to use the Object.keys length
Like so:
console.log(Object.keys(a).length);
If you want to update the length you need to use push. If you are using brackets you are adding a new property to an object (remember that an array is an object).
The length property return the number of elements in the array (not the properties).
var arrA = new Array();
var arrB = new Array();
arrA['propertyOne'] = 1; //add property 'propertyOne' with value 1 to the object arrA
arrA.push(2);
arrB.push(1);
arrB.push(2);
console.log(arrA); // [2, propertyOne: 1]
console.log(arrA[0]); // 2
console.log(arrA['propertyOne']); // 1
console.log(arrA.hasOwnProperty('propertyOne')); // true
console.log(arrA.length); // 1
console.log(arrB); // [1, 2]
console.log(arrB.length); // 2

Possible to push empty slot to an array?

I'm building my own map method to be as close as the native map method.
Since the native map pushes(i think) the changed values into a new array, it still keeps the empty slots. I wasn't able to find a solution to push an empty slot into an array, like this example below.
[1, 2, 3].push(some code) // [1, 2, 3, empty]
I tried pushing an array with one empty item prefixed with a spread operator arr.push(...(new Array(1))) or arr.push(...[,]) but that just pushes undefined.
I solved my problem by not using push and instead assigning values to the array index that way skipped indices will be set to empty.
But I'm writing this post to see if anyone knows that if it's possible to use the push method to push an empty slot to an array.
No, it's not possible, not with the push method. empty can only exist if the array has a certain length, but a whole number property of the array does not exist at some index. This is called a sparse array, and cannot be created with push (or other array methods, if they're called on and with non-sparse arrays).
The only way to do so would be to assign to an index for which a lower index doesn't exist yet.
Look at the results for the below two snippets in your browser console, not the snippet console:
const arr = [];
arr[1] = 'a';
console.log(arr);
Or to set the .length of the array above the last index that the array has:
const arr = [];
arr.length = 1;
console.log(arr);
But the two approaches above are very weird to do and probably have no good reason to be used. Better to avoid sparse arrays entirely.
Keep in mind that an empty slot is different from undefined, which is perfectly possible to have as an array value:
const arr = [];
arr.push(undefined);
console.log(arr);
You can create an empty slot in an array by incrementing the array length:
var a = []
a.push(1)
a.length++
a.push(3)
console.log(a)
console.log(1 in a) // anything at index 1?
Alternatively, you can push something and then delete it:
var a = []
a.push(1)
a.push(2)
a.push(3)
delete a[1]
console.log(a)
console.log(1 in a) // anything at index 1?
There is no need to actually push to a new array in your implementation. You can simply do new Array(this.length) where this.length is the array you are mapping through length.
For example consider this map implementation:
if (!Array.prototype.mapIt) {
Object.defineProperty(Array.prototype, "mapIt", {
value: function(fn) {
if (this === null) {
throw new TypeError('Array.prototype.mapIt called on null or undefined');
}
if (typeof fn !== 'function') {
throw new TypeError('predicate must be a function');
}
let _array = this.filter(x => x != null) // remove empty values
let result = new Array(_array.length) // the new array we will return
for (var i = 0; i < _array.length; i++) {
result[i] = fn.call(arguments[1], _array[i], i, _array) // call the predicate
}
return result;
}
});
}
let arr = [1, 2, , , 3] // the test array
let result = arr.mapIt((c, i, a) =>
console.log(`current: ${c}`, `index: ${i}`, `array: ${a}`) || c + 2)
console.log('result: ', result)
console.log('original array: ', arr)
Hope this helps you with an gives you an idea about a possible map implementation.

How to push new elements to an array with undefined index in JavaScript

I want to create array once and then just push values to it with any index , but i get Cannot read property 'push' of undefined error
I have following scenario
var neg = [];
I want to use push randomly with any index
neg[0].push([1,2]);
or
neg[22].push([1,2]);
right now I want to define manually like neg[0] = []; , Is there any one way where i can just push to any index i want ?
Here's a quick way to do exactly what you want.
var arr = [];
(arr[0]=[]).push([1,2]);
console.log(arr)
Also it's safer to check if an array already exists at this index, otherwise it will be replaced with an empty array – the above code will replace the array with an empty one if it already exists.
// creates an array at index 0 only if there's no array at this index.
// pushes an array of [1, 2] to the existing array at 0 index
// or the newly created empty one.
(arr[0] || (arr[0] = [])).push([1, 2]);;
var arr = [];
arr[0] = [1];
(arr[0]||(arr[0]=[])).push(2,3);
console.log(arr)
Push will add elements to the end of an array. For example:
var neg = [];
neg.push(3); //this will add the number 3 to the end of your array
The problem here is your trying to add a value to an undefined element:
var neg = [];
neg[0].push([1,2]); // <-- neg[0] is not defined at this moment, and you're treating it as an array object.
If you define your elements as an array, you will not get such an error:
var neg = [];
neg[0] = [];
neg[22] = [];
neg[0].push([1,2]);
neg[22].push([1,2]);
Alternatively (and this is probably what you're probably looking for), you can set the value for any element of your array with the desired index:
var neg = [];
neg[0] = [1,2];
neg[22] = [1,2];
You are going to have to set it to an empty array before you can push it.
neg[0] = neg[0] || []
neg[0].push([1,2]);
You can specify how large the array will be if you know ahead of time, for example var neg = new Array(40); will create a new array with 40 undefined elements.
Once that is created, you can change the value at any index as long as 0 <= index <= 39.
You can use array.splice(your_index, 0, your_element); to push an element into an array at the given index.

Javascript - Why returning array.push(x) from a function doens't push the element x into the array?

I'd like to know why the following function works:
function foo(list){
var array = [];
array.push(list);
return array;
}
> foo([1,2,3])
[[1,2,3]]
while this one doesn't:
function foo(list){
var array = [];
return array.push(list);
}
> foo([1,2,3])
1
What's the difference between them?
If you look at the definition of the push method, it returns the length of the array after the push, not the array itself, that is why it is returning 1.
The push() method adds one or more elements to the end of an array and
returns the new length of the array.
You are pushing an array with 3 elements to the new array, so in the new array you have an array as its content thus 1 is returned

javascript datastructure question

I have an array:
myArray = [];
To which I am adding objects:
data = [];
myArray.push( {
elem1: ...,
elem2: data.push(...);
} );
So, elem2 in the object contains an array. How can I, given myArray add new elements to the array in elem2? I tried the following:
myArray[idx].elem2.push("new data");
But got an error saying that elem2.push() is not a method.
The issue line is:
elem2: data.push(...)
data is an array. The push method for arrays does not return the array, it returns the length of the array once the item has been added.
So if you have:
var data = [];
var moreData = data.push(1);
moreData will actually equal 1.
Since the value of elem2 is actually an integer, you are then calling push on that integer. That's where you are getting the error.
The .push() function does not return the array, so that line that tries to set "elem2", well it isn't doing that.
I tried the same and works, look the code:
var a = [];
a.push({
a: []
});
a[0].a.push("a");
alert(a[0].a[0]); // return 'a'
in your array you must add another array, not the array.push(), because it will return the position that elements was inserted.

Categories

Resources