The following code:
var arr1 = [1,2,3];
var obj1 = {};
for (var j = 0; j < arr1.length; j++) {
if (obj1[j.toString()])
obj1[j.toString()] = obj1[j.toString()].push(j)
else
obj1[j.toString()] = [].push(j);
}
produced the following output:
obj1
=> { '0': 1, '1': 1, '2': 1 }
and I would just kindly like to know why.
(I'm aware now that the following code:
var arr1 = [1,2,3];
var obj1 = {};
for (var j = 0; j < arr1.length; j++) {
if (obj1[j.toString()])
obj1[j.toString()] = obj1[j.toString()].push(j)
else {
obj1[j.toString()] = [];
obj1[j.toString()].push(j);
}
}
will give me my desired output:
obj1
=> { '0': [ 0 ], '1': [ 1 ], '2': [ 2 ] }
)
Because, as per the documentation, the Array.prototype.push()
method returns the Array length, not the array itself.
You may prefer the concat
method like so:
var arr1 = [1,2,3];
var obj2 = {}
for (var j = 0; j < arr1.length; j++) {
var js = j.toString()
if (obj2[js]) {
obj2[js] = obj2[js].concat([j])
} else {
obj2[js] = [j]
}
}
console.log(obj2) // => { '0': [ 0 ], '1': [ 1 ], '2': [ 2 ] }
// shorter version
var obj3 = {}
for (var j = 0; j < arr1.length; j++) {
var js = j.toString()
obj3[js] = [].concat(obj3[js] || [], [j])
}
console.log(obj3) // => { '0': [ 0 ], '1': [ 1 ], '2': [ 2 ] }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With