简体   繁体   中英

Combing object array by removing duplicates in javascript

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

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)
};

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM