0

Below is the array that has 2 elements with Plan as name.I want to group the array using Javascript by name but the StartDate should be the minimum of all startdates that has name as Plan and EndDate should be max of all enddates that has name as plan.I want to group the elements and not sort them.

[{"Name":"Define","StartDate":"2015-04-09","EndDate":"2015-04-22"},
{"Name":"Plan","StartDate":"2015-04-22","EndDate":"2015-04-29"},
{"Name":"Plan","StartDate":"2015-04-30","EndDate":"2015-05-14"]}]

So my final array should be like below

 [{"Name":"Define","StartDate":"2015-04-09","EndDate":"2015-04-22"},
    {"Name":"Plan","StartDate":"2015-04-22","EndDate":"2015-05-14"]}]

I have got stucked in building the logic.Help appreciated.

Viral
  • 61
  • 1
  • 10

1 Answers1

0

Here's how you can do it using underscore.js (http://underscorejs.org/)

arr = [{"Name":"Define","StartDate":"2015-04-09","EndDate":"2015-04-22"},
{"Name":"Plan","StartDate":"2015-04-22","EndDate":"2015-04-29"},
{"Name":"Plan","StartDate":"2015-04-30","EndDate":"2015-05-14"}];

result = _.chain(arr)
 .groupBy(function(e){ return e.Name })
 .pairs()
 .map(function(e){  
  return {
   Name: e[0],
   StartDate: _.chain(e[1]).sortBy(function(e){ return new Date(e.StartDate).getTime(); }).first().value().StartDate,
   EndDate: _.chain(e[1]).sortBy(function(e){ return -1 * new Date(e.EndDate).getTime(); }).first().value().EndDate
  }
 })
 .value()
Furqan Zafar
  • 1,461
  • 1
  • 13
  • 17
  • Can you help me doing this with simple js or jquery. – Viral Apr 16 '15 at 14:25
  • Thanks a lot.I have now used underscore.can you help if my array contains one more element eg Id ,how do I get that? – Viral Apr 16 '15 at 15:42
  • Eg : [{"Id":"1","Name":"Define","StartDate":"2015-04-09","EndDate":"2015-04-22"}, {"Id":"2","Name":"Plan","StartDate":"2015-04-22","EndDate":"2015-04-29"}, {"Id":"2","Name":"Plan","StartDate":"2015-04-30","EndDate":"2015-05-14"]}] – Viral Apr 16 '15 at 15:43
  • Furqan , What changes shall I make in the code to get some additional parameter from array.My new array looks like one above. – Viral Apr 17 '15 at 05:00
  • Just add Id: _.first(e[1]).Id to the object returned by the last map function. – Furqan Zafar Apr 17 '15 at 07:51