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?
asked Aug 14, 2015 at 11:55
Tolgay Toklar
4,3538 gold badges49 silver badges77 bronze badges
2 Answers 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);
answered Aug 14, 2015 at 11:57
Paul Boutes
3,3152 gold badges21 silver badges22 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Kiran Shinde
no need to make object he can do var groupUserCounter=[] and the same code you have provided
Paul Boutes
Yep i've edited the response, but when I use a for in loop, i prefer to iterate over an object.
$.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"] ]
answered Aug 14, 2015 at 12:30
Dharma
3,0093 gold badges25 silver badges38 bronze badges
Comments
lang-js