Reputation: 336
I an array of objects. Each object has a date property and a string property. I also have an empty array. I cant figure out the logic to push the string based on date oldest to newest .
const oldToNew = []
for (const baseId in results[key][test]) {
// log the array of objects
//example [{string: 'test', date: '2019-03-04T10:36:37.206000Z'}, {string: 'test1', date: '2019-03-010T10:36:37.206000Z'}]
console.log(results[key][test][baseId])
results[key][test][baseId].forEach(element => {
});
}
// I want the value to be [test, test1]
Upvotes: 0
Views: 1091
Reputation: 1960
Use Array.sort to compare the date
property of each Object against the one before it - then use Array.map to return an Array of all the items 'string
properties.
Update no need to parse
the date timestamp.
const items = [{string: 'test4', date: '2019-03-04T10:36:37.206000Z'}, {string: 'test1', date: '2019-03-10T10:36:37.206000Z'}, {string: 'test2', date: '2019-03-09T10:36:37.206000Z'}, {string: 'test3', date: '2019-03-07T10:36:37.206000Z'}]
const strings = items
.sort((a, b) => b.date > a.date)
.map(({ string }) => string)
console.log(strings)
Upvotes: 1
Reputation: 156
You need to sort initial array with sort
and then extract strings with map
something like this:
array.sort((a, b) => a.date < b.date).map(el => el.string);
Upvotes: 1