Skip to content Skip to sidebar Skip to footer

Group Javascript Array Object By Same Key

I have an array of object some with same month name but different values based on day. How do we group array object based on same property value for example: [ { month: 'Jan', val

Solution 1:

You could take a Map and reduce the array by adding the value to the month nad get new arrays from the grouped result.

var data = [{ month: 'Jan', value: 3 }, { month: 'Jan', value: 3.5 }, { month: 'Feb', value: 2.1 }, { month: 'Mar', value: 6 }, { month: 'Apr', value: 4.3 }, { month: 'May', value: 5.5 }, { month: 'Jun', value: 7 }, { month: 'Jun', value: 9 }, { month: 'Jul', value: 7 }, { month: 'Jul', value: 9 }, { month: 'Jul', value: 7 }, { month: 'Aug', value: 9 }, { month: 'Sep', value: 9 }, { month: 'Sep', value: 9 }, { month: 'Oct', value: 8 }, { month: 'Oct', value: 5 }, { month: 'Oct', value: 3 }, { month: 'Nov', value: 12 }, { month: 'Nov', value: 19.5 }],
    result = Array.from(
        data.reduce(
            (m, { month, value }) => m.set(month, (m.get(month) || 0) + value),
            newMap
        ),
        ([month, value]) => ({ month, value })
    );

console.log(result);
.as-console-wrapper { max-height: 100%!important; top: 0; }

Solution 2:

A simple human-readable solution can be as follows:

varinput= [ { month:'Jan', value:3 },
  { month:'Jan', value:3.5 },
  { month:'Feb', value:2.1 },
  { month:'Mar', value:6 },
  { month:'Apr', value:4.3 },
  { month:'May', value:5.5 },
  { month:'Jun', value:7 },
  { month:'Jun', value:9 },
  { month:'Jul', value:7 },
  { month:'Jul', value:9 },
  { month:'Jul', value:7 },
  { month:'Aug', value:9 },
  { month:'Sep', value:9 },
  { month:'Sep', value:9 },
  { month:'Oct', value:8 },
  { month:'Oct', value:5 },
  { month:'Oct', value:3 },
  { month:'Nov', value:12 },
  { month:'Nov', value:19.5 } ];varresult= [];for(vari=0;i<input.length;i++) {
    vardata=input[i];varfound=false;for(varj=0;j<result.length;j++) {
        if(result[j].month===data.month) {
            found=true;result[j].value+=data.value;break;
        }
    }
    if(!found) {
        result.push(data);
    }
}

//Theresultarrayisyourdesiredresultconsole.log(result);

Solution 3:

 result = input.reduce(function(res, value){
            if (!res[value.month]) {
                res[value.month] = {
                    month: value.month,
                    value: 0
                }
                result.push(res[value.month])
            }
            res[value.month].value += value.value
            return res;
           }, {});
             console.log(result)

Post a Comment for "Group Javascript Array Object By Same Key"