Tolgay Toklar
Tolgay Toklar

Reputation: 4343

Javascript array inside array

I am creating an array like this:

var groupUserCounter=[];
groupUserCounter["asd"]=1;
groupUserCounter["asd2"]=2;
var groupC=[];

for(var key in groupUserCounter) {
   groupC.push(key);
}

console.log(groupC);

Output:

Array [ "asd", "asd2" ]

But I need something like this:

Array [ ["asd"], ["asd2"] ]

How can I achive this?

Upvotes: 0

Views: 82

Answers (2)

Dharma
Dharma

Reputation: 3013

$.makeArray() functions returns any object into a native Array.just like below

$.each(groupUserCounter, function(index, value) { 
     groupC.push($.makeArray( value));
});
console.log(groupC);//something like this what u expected Array [ ["asd"], ["asd2"] ]

Upvotes: 1

Paul Boutes
Paul Boutes

Reputation: 3315

When you push your key into groupC, you have to push a key array, not just the value.

  var groupUserCounter=[];
  groupUserCounter["asd"]=1;
  groupUserCounter["asd2"]=2;
  var groupC=[];

  for(var key in groupUserCounter) {
     groupC.push([key]);
  }

  console.log(groupC);

EDIT

A more elegant way is using .keys() and .map() method.

  var groupUserCounter=[];
  groupUserCounter["asd"]=1;
  groupUserCounter["asd2"]=2;

  var groupC = Object.keys(groupUserCounter).map(function(elm){
    return [elm]
  });

  console.log(groupC);

Upvotes: 2

Related Questions