I have an array of objects of the form:
{productID: '15', name: 'Pepsi', category: 'food/beverages', dateAdded: '2015-12-21T17:42:34Z'}
I want to find the 5 oldest items by comparing the dateAdded strings. I have tried a few inefficient loops and failed with reduce(), but I feel there's a more efficient way. How can I accumulate the 5 oldest items?
a simple sort/slice will do it - the format of the date means you can just do a localeCompare in your sort callack ... `
const array = [
{productID: '15',name: 'Pepsi',category: 'food/beverages',dateAdded: '2015-12-21T17:42:34Z'},
{productID: '13',name: 'Coke',category: 'food/beverages',dateAdded: '2015-12-20T17:42:34Z'}
];
const top5 = array
.sort(({dateAdded: a}, {dateAdded: b}) => a.localeCompare(b))
.slice(0, 5);
console.log(top5);
You can Sort by datetime like below.
array.sort((firstEl, secondEl) =>
new Date(firstEl.dateAdded).getTime() - new Date(secondEl.dateAdded).getTime())
.slice(0, 5);
const array = [
{ productID: '0', name: 'Pepsi', category: 'food/beverages', dateAdded: '2015-12-21T17:42:34Z' },
{ productID: '1', name: 'Coke', category: 'food/beverages', dateAdded: '2015-10-20T17:42:34Z' },
{ productID: '2', name: 'Coke', category: 'food/beverages', dateAdded: '2015-11-20T17:42:34Z' },
{ productID: '3', name: 'Coke', category: 'food/beverages', dateAdded: '2015-08-20T17:42:34Z' },
{ productID: '4', name: 'Coke', category: 'food/beverages', dateAdded: '2015-01-20T17:42:34Z' },
{ productID: '5', name: 'Coke', category: 'food/beverages', dateAdded: '2015-03-20T17:42:34Z' },
{ productID: '6', name: 'Coke', category: 'food/beverages', dateAdded: '2016-10-20T17:42:34Z' },
{ productID: '7', name: 'Coke', category: 'food/beverages', dateAdded: '2017-10-20T17:42:34Z' },
];
const newArr = array.sort((firstEl, secondEl) => new Date(firstEl.dateAdded).getTime() - new Date(secondEl.dateAdded).getTime()).slice(0, 5);
console.log(newArr);
Sort the items by dateAdded then take the top 5, which should be the oldest