Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: unexpected behavior pushing into empty array

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 ] }

)

like image 218
anatta Avatar asked Mar 02 '16 19:03

anatta


1 Answers

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 ] }
like image 53
cl3m Avatar answered Nov 14 '22 21:11

cl3m