Vikram Sethumadhavan Vikram Sethumadhavan - 3 months ago 16
Javascript Question

underscorejs groupby and filter

I have an array of objects. I would like to

groupby
&
filter(remove)
the object, category which is undefined. Please refer the script below for more clarity :

arrayFlatten = [
{
area:"Digital",
category:undefined,
qId:"q11",
qqId:"step1",
type:"Reduce",
val:1,
userId:1,
weightedAverage:0
},
{
area:"Digital",
category:"Analytics",
qId:"q1",
qqId:"step1",
type:"Reduce",
val:1,
userId:1,
weightedAverage:0
},
{
area:"Digital",
category:"Analytics",
qId:"q1",
qqId:"step2",
type:"Reduce",
val:1,
userId:1,
weightedAverage:0
}
]


The command used to sort using group by

var groupCategory = _.groupBy(arrayFlatten,'category');
console.log(groupCategory);


The expected result is supposed to look like:

arrayFlatten = [
{
area:"Digital",
category:"Analytics",
qId:"q1",
qqId:"step1",
type:"Reduce",
val:1,
userId:1,
weightedAverage:0
},
{
area:"Digital",
category:"Analytics",
qId:"q1",
qqId:"step2",
type:"Reduce",
val:1,
userId:1,
weightedAverage:0
}
]

Answer
filteredArray = _.filter(
    arrayFlatten,
    function (obj) {
        return obj.category !== undefined;
    }
);

filteredArray will contain your array with no undefined categories.

You can also do this without underscore in most modern browsers, using Array.filter() described here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Comments