This question already has answers here:
Using Array.map with new Array constructor
(5 answers)
Closed 3 years ago.
If I write this code: Array(3).map( () => ({ a:1 }) ) I get Array(3) [ <3 empty slots> ] instead of an array of 3 objects. Why is that?
As far as I know, Array(3) will produce an array of undefined elements with length 3. And for instance, [1, 2, 3].map( () => ({ a:1 }) ) produces the expected output. This is true also using any other array with length 3. I'm intrigued.
Array(3) creates an empty array of length 3. Or as an object it would be { length: 3 }. With, e.g. Array(Array(3)) you would create an array with undefineds { 0: undefined, 1: undefined, 2: undefined, length: 3 }. And .map only iterates over existing keys.
Related
This question already has answers here:
Converting JavaScript object with numeric keys into array
(17 answers)
How to convert an Object {} to an Array [] of key-value pairs in JavaScript
(21 answers)
Closed 10 months ago.
I have an object with these key-value pairs. This object comes from an API which I am calling :
APIName(obj).subscribe((res:any) => {
console.log(Object.values(res.data));
})
data = {
0 : 1,
1: 3,
2: 7,
3: 10
....so on
}
simply put it is an object of numbers and my desired output is (a simple array) :
data = [1,3,7,10]
I've tried Object.value and Object.key it still converts it into an object. Any help?
First of all if your data is not sorted by key. Then sort it. and iterate through object and push to array.
var data = {
1: 1,
0: 3,
2: 7,
3: 10
};
let sortedKeys = Object.keys(data).sort();
let arrayOfData = [];
// iterate method
sortedKeys.forEach((key) => {
arrayOfData.push(data[key]);
});
console.log(arrayOfData);
This question already has answers here:
JS : Convert Array of Strings to Array of Objects
(1 answer)
Convert array of string to array of object using es6 or lodash
(4 answers)
Closed 1 year ago.
I have an array of objects as shown below
Array(2)
0: "104635ac-4b9a-3f7a-d4f8-e8badca83d58"
1: "547d57b7-ddc7-a481-95e4-ccfe2a6404a8"
I want to add two more properties one named productId and one name quantity to each element of this array of Objects.
The final outcome should be as follows.
{
"productId": "104635ac-4b9a-3f7a-d4f8-e8badca83d58",
"quantity": 1,
},
{
"productId": "547d57b7-ddc7-a481-95e4-ccfe2a6404a8",
"quantity": 1,
}
Can someone please let me know how to achieve this?
You can use Array.map to map through the array and construct an object:
const arr = ["104635ac-4b9a-3f7a-d4f8-e8badca83d58","547d57b7-ddc7-a481-95e4-ccfe2a6404a8"]
const result = arr.map(e => ({quantity: 1, productId: e}))
console.log(result)
This question already has answers here:
What is empty inside an array? e.g. [empty X 5]
(2 answers)
Undefined values in Array(len) initializer
(5 answers)
JavaScript "new Array(n)" and "Array.prototype.map" weirdness
(14 answers)
Closed 2 years ago.
What is the difference between the undefined elements in JavaScript arrays:
created directly,
created with elision?
Elements of case 1. and 2. both have undefined types and values, but the ones born in elision don't have indexes (or any enumerable properties, their array has a correct Array.length that's clear). Can you give some background on this?
Example:
// case 1.
const undefineds = [undefined, undefined, undefined].map((el, i) => i)
console.log(undefineds, undefineds.length, 'undefineds')
// case 2.
const empties = [,,,].map((el, i) => i)
console.log(empties, empties.length, 'empties')
Output:
Array [0, 1, 2] 3 "undefineds"
Array [undefined, undefined, undefined] 3 "empties"
Note: In case 2. I am aware of not just the indexes i would be undefined, but anything returned from the iteration, e.g.: [,,,].map((el, i) => 'puppies') => [undefined, undefined, undefined].
This question already has answers here:
Undefined values in Array(len) initializer
(5 answers)
Closed 5 years ago.
Suppose we have 3 arrays:
var arr1 = [undefined, undefined, undefined];
var arr2 = [, , ,];
var arr3 = new Array(3);
Are all of them identical in JavaScript?
If we wants to use undefined as default value for fixed size array, can we use them interchangeably?
The second two are the same (though the second one might cause issues on some browsers), but the first is different.
The first one
var arr1 = [undefined, undefined, undefined];
makes explicit assignments to the first three indexes in the array. Even though you're assigning undefined, the fact that indexes 0, 1, and 2 are targets of assignment operations means that those elements of the array will be treated as "real" by methods like .reduce():
[undefined, undefined, undefined].reduce(function(c) { return c + 1; }, 0);
// 3
[,,].reduce(function(c) { return c + 1; }, 0);
// 0
Many of the Array.prototype methods skip uninitialized array elements.
This question already has answers here:
(new Array(10)).map(function() { return 1;}) returns [, , , , , ...] ... Why? [duplicate]
(3 answers)
Closed 7 years ago.
Trying to find a way to inline the creation of an array of data given its size, i tried
var n = 4;
var data = (new Array(n)).map(function(x) { return 1 });
which gave me
[undefined, undefined, undefined, undefined]
Regarding that
new Array(n)
gives
[undefined, undefined, undefined, undefined]
and that
[undefined, undefined, undefined, undefined].map(function(x) { return 1 });
returns
[1, 1, 1, 1]
I would expect to be able to chain the Array constructor and the map function.
Any insights on that behavior ?
new Array(n) creates an array of size n, but with no elements in it. This is called a sparse array. Though there are no elements in the array, the browser represents them as undefined. And Array.prototype.map will ignore the array elements which are not defined yet.
Quoting from the ECMA 5.1 Specification for Array.prototype.map,
callbackfn is called only for elements of the array which actually exist; it is not called for missing elements of the array.
To be able to chain the map function, you might want to do like this
console.log(Array.apply(null, {length: n}).map(function(x) { return 1 }));
# [ 1, 1, 1, 1 ]