JavaScript code to fetch range of dates from array of objects depending on one attribute of the array using array.reduce()

I also enjoy using reduces. It’s very handy for a lot of cases.

var developers = [
{ name: "Joe", age: 23, overallLevel: "high", date: "Aug 14, 2015" },
{ name: "Sue", age: 28, overallLevel: "advanced", date: "Aug 11, 2015" },
{ name: "Jon", age: 32, overallLevel: "high", date: "Aug 10, 2015" },
{ name: "Bob", age: 24, overallLevel: "high", date: "Sept 07, 2015" },
{ name: "Johnson", age: 23, overallLevel: "advanced", date: "Aug 20, 2015" },
{ name: "Paul", age: 25, overallLevel: "basic", date: "Jan 30, 2016" },
{ name: "Jane", age: 27, overallLevel: "intermediate", date: "Aug 30, 2016" },
{ name: "Chris", age: 20, overallLevel: "basic", date: "Aug 1, 2016" },
{ name: "Susan", age: 25, overallLevel: "basic", date: "Dec 12, 2015" },
{ name: "Jenny", age: 23, overallLevel: "intermediate", date: "Aug 30, 2016" },
{ name: "Stone", age: 25, overallLevel: "basic", date: "June 13, 2016" },
],
reduced = developers.reduce((p,c) => {var d = new Date(c.date);
                                      p[c.overallLevel] ? d < p[c.overallLevel][0] && d < p[c.overallLevel][1] ? p[c.overallLevel][0] = d
       	                                                                                                       : p[c.overallLevel][1] = d
                                                        : p[c.overallLevel] = [d,d];
                                      return p},{});
reduced = Object.keys(reduced).reduce((p,c) => (p[c] = p[c].map(e => e.toDateString(2)), p),reduced);
       
console.log(reduced);

Browse More Popular Posts

Leave a Comment