5

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

)

1
  • 2
    Well, [] is the same as Array.prototype, there is no empty array, and you're not pushing to anything inside obj. The second code snippet is the correct way of doing it, where you actually create an empty array Commented Mar 2, 2016 at 19:48

1 Answer 1

11

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 ] }
Sign up to request clarification or add additional context in comments.

2 Comments

Did not notice the first snippet. +1
Confirmed. [1,2,3].push(60); // 4; [].push(90); // 1; Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.