-2

I have an array of objects -

[
{ name:'abc',
  lRange: '2020-01-01',
  hRange: '2020-01-22',
},

{ name:'abc',
  lRange: '2020-01-01',
  hRange: '2020-01-22',
},
{ name:'def',
  lRange: '2020-01-15',
  hRange: '2020-01-30',
},
{ name:'ghi',
  lRange: '2020-02-10',
  hRange: '2020-02-22',
}
]

I need to get the min Date and Max Date range combining all the dates lRange and hRange dates - there will be a overlap of the dates too.

I have tried sorting by date times but that is not giving me the correct range. any ideaS?

3 Answers3

1

Here's one way to do it, though I suspect there are more elegant methods. It converts each string date into a date object and compares them. Finally it takes the min and max and converts them back into readable strings.

let dates = [{
    name: 'abc',
    lRange: '2019-02-01',
    hRange: '2020-01-22',
  },

  {
    name: 'abc',
    lRange: '2020-01-01',
    hRange: '2020-01-22',
  },
  {
    name: 'def',
    lRange: '2020-01-15',
    hRange: '2020-01-30',
  },
  {
    name: 'ghi',
    lRange: '2020-02-10',
    hRange: '2020-02-22',
  }
]

let output = {}

dates.forEach(obj => {
  if (!output.min) {
    output.min = new Date(obj.lRange);
    output.max = new Date(obj.hRange);
  } else {
    output.min = Math.min(output.min, new Date(obj.lRange))

    output.max = Math.max(output.max, new Date(obj.hRange))

  }

})
//convert back to date strings
 output.min =  new Date(output.min).toISOString().split("T")[0]
 output.max =  new Date(output.max).toISOString().split("T")[0]

 console.log(output)
Kinglish
  • 23,358
  • 3
  • 22
  • 43
1

You can use flatMap to get all dates and then sort it. After sorting the first element (i.e element at index 0) is minRange and element at last index is maxRange.

const arr = [
  { name: "abc", lRange: "2020-01-01", hRange: "2020-01-22" },
  { name: "abc", lRange: "2020-01-01", hRange: "2020-01-22" },
  { name: "def", lRange: "2020-01-15", hRange: "2020-01-30" },
  { name: "ghi", lRange: "2020-02-10", hRange: "2020-02-22" },
];

const sortedResult = arr
  .flatMap((obj) => [obj.lRange, obj.hRange])
  .sort((a, b) => new Date(a) - new Date(b));

const result = {
  min: sortedResult[0],
  max: sortedResult[sortedResult.length - 1],
};

console.log(result);
DecPK
  • 24,537
  • 6
  • 26
  • 42
0

You can pull the lRagnes and hRanges out into individual arrays if it makes it easier for you.

var lDates = [];
var hDates = [];

yourArray.map((innerObjects) => {
    lDates .push(innerObjects.lRange);
    hDates .push(innerObjects.hRange);
});