Strange behavior when add element to array by key [duplicate] - javascript

This question already has answers here:
Javascript array length incorrect on array of objects
(3 answers)
Closed 8 years ago.
I don't understand why is array so strange when I add element by key.
For example:
var test = new Array();
test['a'] = 'aaa';
test['b'] = 'bbb';
test.length == 0; // true. Why?
And when I run:
test.map(function(el){
console.log(el);
});
// nothing print. Why?
When I add element with push method everything works OK. Thanks

Arrays in javascript are not associative, you can't set keys like that i.e.
var test = [];
test.push('aaa');
test.push('bbb');
// OR
test[0] = 'aaa';
test[1] = 'bbb';
test.length = 2

Related

When uniquely updating an object in an array in Javascript, the objects values are all changing [duplicate]

This question already has answers here:
How to update one Javascript object array without updating the other [duplicate]
(3 answers)
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 3 years ago.
I currently have an array of objects called posts.
for(var i = 0; i < posts.length; i++){
let post = posts[i]
let { item, category } = post
let postCollections = categories[category]
for(var col in userCollections[category]){
let items = userCollections[category][col].items
if(items && col){
postCollections[col]['item'] = item
console.log("HERE!, item)
if(item in items){
postCollections[col]['joined'] = true
}else{
postCollections[col]['joined'] = false
}
}
}
posts[i]['collections'] = postCollections
}
When this is run, the print out for "HERE!" shows the item value is unique. When I print out posts and look at the value for key items they all show the same item.
This was a tough solve. Turns out the line where I set postCollections was using the same object over and over again. Copying the object like this has done the trick:
let postCollections = JSON.parse(JSON.stringify(categories[category]));

Pushing elems into an array conditionally [duplicate]

This question already has answers here:
Array.push() if does not exist?
(30 answers)
Remove duplicates form an array
(17 answers)
Closed 4 years ago.
I have a simple array with a few elems & a new elem , trying to check the elems with a function , push the new elem into the array if not already present & ignore it if it is.
I created a function with an if /else statement but the code always adds the new item to the array.
var arr=['a','b'];
var newElem='c';
function f(){
for(var i=0; i<arr.length; i++){
if(arr[i] == newElem){ console.log('Exists');return }
else {arr.push(newElem);console.log(arr); return }
}
}
f();
The code works fine if the new item not present in the array but if it's ,the new elem still being pushed into the array?
Pls anyone could help , don't want to ask the teacher , it looks so simple ?
Check if element exists first like so:
const arr = ['a', 'b'];
const newElem = 'c';
if (arr.indexOf(newElem) === -1) {
arr.push(newElem);
}

Loop is adding too many items to the final array [duplicate]

This question already has answers here:
Array.fill(Array) creates copies by references not by value [duplicate]
(3 answers)
Closed 4 years ago.
When i use Array.fill to fill a multidimensional array, i get a weird behaviour when pushing to one of the arrays:
var arr = Array(2).fill([]);
arr[0].push(5);
console.log(arr);
//=> prints [[5], [5]]
fill is essentially doing this:
var content = [];
for (var i = 0; i < 2; i += 1) {
arr[i] = content;
}
So, your array will have a reference to the array you've passed to fill in each property.
It sounds weird, but what your code actually does is create an array ([]) and put a reference for that array in each of the items of the Array(2). So whenever you change that reference - every array that is referenced to that Array is changed.
It's exactly the same as:
var a = [];
var arr = Array(2).fill(a);
a.push(5);
console.log(arr[0][0], arr[1][0]);
a[0] = 2;
console.log(arr[0][0], arr[1][0]);
You can see that the values inside the arr are affected by the change to the a array.

Why is array = Array(10).fill(Array(20).fill(-1)) not the same as array [[-1,..,-1], ..., [-1,..,-1]]? [duplicate]

This question already has answers here:
Array.fill(Array) creates copies by references not by value [duplicate]
(3 answers)
Closed 4 years ago.
I tried to create a 2-dimensional array in javascript. (Actually, the code is written in typescript and will be used to style DOM Elements with Angular2 but, as far as I am concerned, it shouldn't have any effect on the result in this case.)
First way:
arrayi = Array(10).fill(Array(20).fill(-1))
Second way:
array = [];
for(var i: number = 0; i < 10; i++) {
array[i] = [];
for(var j: number = 0; j< 20; j++) {
array[i][j] = -1;
}
}
If I call array[1][2] = 2; it does what I expected, what means setting one element in the 2-dimensional array to 2.
However, if I call arrayi[1][2] = 2; every element arrayi[x][2] will be set to 2. (With x element {0,1,2,...,9})
Why is that? I don't understand it. So it would be nice if someone could explain it to me.
The arrays are defined as array: number[][] and arrayi: number[][] in typescript.
arrayi = Array(10).fill(Array(20).fill(-1)) fills with the same array.
You can even rewrite it like this
const arr1 = Array(20).fill(-1)
const arrayi = Array(10).fill(arr1)
console.log(arrayi.every(item => item === arr1)) //true
The reason is that you create one instance of array with 20 elements and put this single instance into each element of root array

Javascript: Setting all array values to the same [duplicate]

This question already has answers here:
Initializing an Array with a Single Value
(12 answers)
Closed 8 years ago.
I want to make a new array (of X elements) with all the elements set to 0.
X is set before.
Anyone could make the most compact and easy code for that? Thank you for your
help.
Just create a function:
function makeArray(size, defaultValue) {
var arr = [];
for (var i = 0; i < size; i++) arr.push(defaultValue);
return arr;
}
var myArr = makeArray(10, 0);

Categories