This question already has answers here:
Initializing and filling multi dimension array in javascript
(2 answers)
Closed 4 years ago.
So I have been trying to create an empty 2d array and trying to push values into it.
The following code is as follows.
// Create an array like [[],[]]
let series = new Array(2).fill([]);
//try to push value into the array in position 0 like [[5],[]]
series[0].push(5); // output here is [[5],[5]]
How can I push element to the array at index 0?
There is something I'm missing. Any help is appreciated!!
When you use fill([]) it creates one array and fills everything with a reference to that one array. You can use something like map() or Array.from() which will create a new array object with each iteration:
let series = Array.from({length: 2}, () => []);
series[0].push(5);
console.log(series)
Use [...Array(2)].map(a=>[]); instead.
When you use fill you assign the same object reference to everything
let series = [...Array(2)].map(a=>[]);
series[0].push(5);
console.log(series)
Related
This question already has answers here:
Copy array by value
(39 answers)
Closed 3 years ago.
So I need the original(argument) array to stay the same, AND have another array (array2) with it's values to make some changes on it but mantain the original(argument) array intact.
Example:
let wtf = function(array){
let array2 = array
array2[0] = array2[0].replace(array2[0][0],"1")
console.log( array + " " + array2)
}
wtf(["a","b"])
Result in console:
1,b 1,b
BUT I need a,b 1,b
(that comes from: array = a,b and array2 = 1,b )
Thanks!
I think this is a reference value vs a clone value problem.
With your let array2 = array line, I think you're creating a reference to the same in-memory object, so you're actually modifying a single array twice, even though it looks like you've created another one.
To create a 'true' clone you can try something like:
let array2 = JSON.parse(JSON.stringify(array));
This question already has answers here:
JavaScript Object Literals & Array Literals
(4 answers)
Closed 5 years ago.
I have five user variables with different names. I'd like them to end up in an array, and am wondering if I can do the assignment to multiple array indices in a single line. Currently, if I do this
var users = {user5k, user10k, user15k, user20k, user25k};
I can't index it later (says users[0] is undefined). So I want the indices built in to the assignment. Something along these lines:
var users = {};
users[0:4] = {user5k, user10k, user15k, user20k, user25k};
This doesn't seem possible in JavaScript, meaning I have to do this:
var users = {};
users[0] = user5k;
users[1] = user10;
// ... et cetera
Is there a way to accomplish the first solution?
When you use {} you're creating an object, not an array. Use [] for arrays.
var users = [user5k, user10k, user15k, user20k, user25k];
If you want to replace part of an array that already exists, you can use Array.prototype.splice()
var users = [];
users.splice(0, 4, [user5k, user10k, user15k, user20k, user25k]);
This question already has answers here:
Javascript Array Concat not working. Why?
(7 answers)
Closed 6 years ago.
I know this has been asked a lot of times, but I cannot get it to work.
I have an empty array a
var a = [];
and an array with an object b
var b = [{
title: 'test'
}]
I want to join them so a will look exactly like b.
The idea is to do this inside a for loop so a would be added a new item each time.
By using a.concat(b), a results in an empty array.
Not sure what I am missing.
Per Array.prototype.concat()
This method does not change the existing arrays, but instead returns a new array.
You need to assign this operation back to a
a = a.concat(b)
You need to assign result of that call to a. a = a.concat(b)
This question already has answers here:
How to get subarray from array?
(5 answers)
Closed 7 years ago.
Is there a way (like we have in C# generics/linq list.take...) that can take a range of elements of an array in the argument while calling a function, without having to create a new array?
//a simple array with some elements
myArray;
//just to show what I mean...pass the first five elemtns of array to the function
doSomethingWithArray(myArray[0,4]);
function doSomethingWithArray(items) {
//do stuff
}
Sounds like you might be looking for slice.
doSomethingWithArray(myArray.slice(0, 4))
Slice takes start and end parameters and returns a shallow copy of the items in the array that fall within that range. If you want to mutate the array you can consider splice.
Note that the end index is non-inclusive, i.e. myArray.slice(0,4), in the example, returns only elements in the range [0 .. 3].
This question already has answers here:
Sort array of objects by string property value
(57 answers)
Closed 8 years ago.
I have an array of objects, and i am basically breaking my head on sorting it,my array is something like dis :
var myArray = [{1:3},{3:19},{5:53},{6:26},{e:53},{c:107},{B: 2},{f: 5}];
But i have to sort this in such a way that my final output is something like this:
myArray = [{c:107},{5:53},{e:53},{6:26},{3:19},{f: 5},{1:3},{B: 2}];
i.e.; based on the value in each object of array element, the array should sorted in descending order.
Thank you in advance.
You can simply use a comparator function in Array.prototype.sort like this
console.log(myArray.sort(function(first, second) {
return second[Object.keys(second)[0]] - first[Object.keys(first)[0]];
}));
Since the key will be different in every object, we get the actual list of keys and taking only the first item in it.