Skip to content Skip to sidebar Skip to footer

Group Array According To The Same Element They Have Using Javascript

I have this kind of array that has date and id only. temp:[ 0:{ id:'1' date:'2017-11-07' } 1:{ id:'2' date:'2017-11-05' } 2:{ id:'3'

Solution 1:

You could take a hash table for defining the same group and push any new group to the result set.

var data = [{ id: "1", date: "2017-11-07" }, { id: "2", date: "2017-11-05" }, { id: "3", date: "2017-11-05" }, { id: "4", date: "2017-11-01" }, { id: "5", date: "2017-11-01" }],
    hash = Object.create(null),
    result = [];

data.forEach(function (o) {
    if (!hash[o.date]) {
        hash[o.date] = [];
        result.push(hash[o.date]);
    }
    hash[o.date].push(o);
});

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

Post a Comment for "Group Array According To The Same Element They Have Using Javascript"