Если вы не хотите изменять исходный массив, и если вы хотите удалить «самое низкое» значение, вы можете сделать один цикл for, который будет:
- Отслеживать предыдущийзначение.
- Сравните предыдущее значение с текущим.
- Отфильтруйте значение в соответствии с вашими потребностями.
Комментарии к коду приведены ниже, это решениеподразумевает зацикливание исходного массива только один раз, используя один цикл for-of.
const input = [
{
title: 'Title 1',
startTime: '2019-09-26T06:00:00+0100',
endTime: '2019-09-26T08:30:00+0100'
},
{
title: 'Title 2',
startTime: '2019-09-26T08:00:00+0100',
endTime: '2019-09-26T08:15:00+0100'
},
{
title: 'Title 3',
startTime: '2019-09-26T08:30:00+0100',
endTime: '2019-09-26T09:25:00+0100'
},
{
title: 'Title 4',
startTime: '2019-09-26T09:25:00+0100',
endTime: '2019-09-26T10:25:00+0100'
},
{
title: 'Title 5',
startTime: '2019-09-26T10:25:00+0100',
endTime: '2019-09-26T11:00:00+0100'
}
];
function fixChronologicalItems(arr) {
// Keep track of the previous item.
let res = [], previous;
// Iterate all the items of the array.
for (let i = 0; i < arr.length; i++) {
// assume the current item is the looped one.
let item = arr[i];
// if our accumulator is not empty, acquire its last element considering it the previous item.
if (res[res.length - 1]) previous = res[res.length - 1];
else previous = arr[i], item = arr[i+1], i++; // if it doesn't, consider the current item the previous one, and the current item the next one, so increase the index by one to properly skip the next item.
// Acquire both datetimes.
let [previousDate, nextDate] = [new Date(previous.endTime), new Date(item.endTime)];
// if the previous item's date is before the next one, both items should be kept.
if (previousDate < nextDate) {
res.push(item); // <-- this will become the next "previous".
}
else res.push(previous); // <-- Otherwise, only the greatest date (which is the previous one) should be kept.
}
// finally, return the accumulator.
return res;
}
const res = fixChronologicalItems(input);
console.log(res);