1

I have a data object

data : [
["1", 20],
["1", 24],
["1", 2],
["1", 32],
["1", 23],
["1", 80],
["2", 3],
["2", 32],
["2", 34],
["2", 36],
["2", 36]]

Now I want the object to be grouped like this ie "1" grouped in one array and same for the "2"

"data" : [
["1", [20, 24, 2, 32, 23, 80]],
["2", [3, 32, 34, 36, 36]]
] 
2
  • 5
    What have you tried so far? Where are you getting stuck? Otherwise what is the question? Commented Aug 22, 2015 at 20:52
  • data.forEach(function(element,array,index){ aCategories.push(element[0]); aSeries.push(element[1]); }) }; this gives me all the values into 2 different variable, but i feel this is not an efficient way to proceed. Commented Aug 22, 2015 at 21:10

2 Answers 2

2

Try this (fiddle - look at the console):

var obj = {
    data : [
        ["1", 20],
        ["1", 24],
        ["1", 2],
        ["1", 32],
        ["1", 23],
        ["1", 80],
        ["2", 3],
        ["2", 32],
        ["2", 34],
        ["2", 36],
        ["2", 36]]
};

function group(data) {
    var mapObj = data.reduce(function (map, item) { // create a map of the key: [values]
            var key = item[0];
            var value = item[1];
            map[key] && map[key].push(value) || (map[key] = [value]);
            return map;
        }, {});

    return Object.keys(mapObj).map(function (key) { // map the keys and values back to arrays
        return [key, mapObj[key]];
    });
}

var newObj = {
    data: group(obj.data)
};
Sign up to request clarification or add additional context in comments.

2 Comments

if my data is data : [ [{ "d" : "1", "v" :"one" }, 20], [{ "d" : "1", "v" :"one" }, 24], [{ "d" : "1", "v" :"one" }, 2], [{ "d" : "1", "v" :"one" }, 32], [{ "d" : "1", "v" :"one" }, 23] }; ie the first element of the array is object then how it would be? it is bit confusing me.
If d is the key then var key = item[0].d; If the object itself is the key, that's a problem because after .toString() it will be "[object Object]", and the array would be [[object object], [values]].
0

I don't know what are you trying to achieve, but that's one way you can structure such an array:

   var ones = ["1",[]];
   var twos = ["2",[]];
   var data2 = [];

function go() {

    for(var i = 0; i < data.length; i++) {
       minidata = data[i];


            if(minidata[0] === "1") {
               ones[1].push(minidata[1]);

            } else if ( minidata[0] === "2") {
               twos[1].push(minidata[1]);
            }

    }

   data2.push(ones);
   data2.push(twos);

  console.log(data2);
}

Check the console to see the results.

JSFiddle

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.