archeal anie
archeal anie

Reputation: 260

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"
     date:"2017-11-05"
    }
    3:{
     id:"4"
     date:"2017-11-01"
    }
    4:{
     id:"5"
     date:"2017-11-01"
    }
    ] 

I just want to group it like this

data:[
    0:{
      0:[id:"1",date:"2017-11-07"]
    }
    1:{
      0:[id:"2",date:"2017-11-05"],
      1:[id:"3",date:"2017-11-05"]
    }
    2:{
      0:[id:"4",date:"2017-11-01"],
      1:[id:"5",date:"2017-11-01"]
    }]

I have a code from php, and it work well in,

this is my code in php:

$newTemp = array();
foreach($temp as $value){
  $newTemp[$value['id'].'_'.$value['date']][] = $value;  
}

but I don't know how I will use it in javascript

Can you help me with my code, on how I should group the date of the array

Upvotes: 2

Views: 64

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386654

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

Upvotes: 2

Related Questions