0

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]
3
  • So is it that you want an array[string] of sorted items by date (oldest to newest)? Commented Mar 25, 2019 at 14:56
  • Yep @FrancisLeigh Commented Mar 25, 2019 at 15:06
  • Possible duplicate of Sort Javascript Object Array By Date Commented Mar 25, 2019 at 15:19

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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)

4 Comments

can we do something where there are more than 2 objects in the array
@Karam yes, do you have any stub data? this solution should work for any amount.
@Karam i have added two other items into the Array. if you have some data you would like to use, update your question with it :-)
you do not need to create new Date. ISO8601 is designed for lexicographical sort. so '2007-01-17T08:00:00Z' < '2008-01-17T08:00:00Z' === true

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.