0

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?

2 Answers 2

2

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

2 Comments

no need to make object he can do var groupUserCounter=[] and the same code you have provided
Yep i've edited the response, but when I use a for in loop, i prefer to iterate over an object.
1

$.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"] ]

Comments

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.