0

I am trying to create 2 sort types in my FE with javascript for my items that come from the backend but I don't know what the logic should look like for it. Where can I read about something like this?

The first way would be to sort them by the date (The most recent first) The second way would be to sort them by the total number of the awards (Highest number first)

This is how my data looks like:

[
 {
    awards: {awardOne: 1, awardTwo: 4, awardThree: 8}
    createdAt: "2020-11-13T21:12:50.742Z"
    text: "Some text"
    username: "username"
 },
 {
    awards: {awardOne: 1, awardTwo: 4, awardThree: 8}
    createdAt: "2020-11-13T21:12:50.742Z"
    text: "Some text"
    username: "username"
 },
 {
    awards: {awardOne: 2, awardTwo: 3, awardThree: 2}
    createdAt: "2020-11-13T21:12:50.742Z"
    text: "Some text"
    username: "username"
 },
]
Samuel
  • 103
  • 3
  • 10
  • To achieve that, you need to sort the array by awards first, then by date. That way the date will be the primary sorting criterion. To do that you need a) a way to sum an object's values; look up `Object.values` and `Array.reduce` (the [example on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) adds all values together) b) call `Array.sort` two times –  Nov 19 '20 at 19:42
  • 1
    Duplicate: [How to sort an array of objects by multiple fields?](https://stackoverflow.com/questions/6913512/how-to-sort-an-array-of-objects-by-multiple-fields) –  Nov 19 '20 at 19:44

2 Answers2

1

Here is an example sorting the data by number of awards in each object: code sandbox. I'm reducing the items in each awards object to a single value and comparing those.

To sort by date, you can use localeCompare like others have pointed out and use a similar pattern.

Update: I just added an working example of sorting by date to the same sandbox

pasha_codes
  • 625
  • 2
  • 5
  • 19
  • This does makes sense, but for some reason if I console log sortedByAwards and sortedByDate, I get the same order in the array. Weird ... – Samuel Nov 19 '20 at 20:58
  • Ahh good catch, the date sorting works but awards sorting was broken. I was trying to grab the length of the value returned by `awardsReducer` when the reducer was returning a number already. It's fixed now, check out the sandbox again. I added new labels to each item – pasha_codes Nov 19 '20 at 22:28
  • Good one! Now it's working fine! Thank you :) – Samuel Nov 20 '20 at 07:54
0

I am thinking you can sort the items by date lexiographically.

Using String.prototype.localeCompare your code would something like

data.sort((a, b) => {
   return ('' + a.createdAt).localeCompare(b.createdAt);
}

Source

To sort by number of awards you would need a smaller function, that calculates number of awards, and then write something like:

 data.sort((a, b) => {
   return (calcNumOfAwards(a) - calcNumOfAwards(b))
}