0

I have an array of objects:

const arr = [
  {
    name: 'Kevin',
    timestamp: "1617834779855"
  },
  {
    name: 'Louis',
    timestamp: "1617334735485"
  },
  {
    name: 'Adisson',
    timestamp: "1616530999700"
  },
]

And I need to sort by most recent timestamp and by name in alphabetical order. Right now I have a sort function to sort by the date but Im not sure how to add the name to the sort function as well

const i = arr.sort((a, b) => b.timestamp - a.timestamp);

My first thought was to add another sort function but I dont want it to loop thru the array again because in my app the array is over 1000 items length

ousmane784
  • 306
  • 1
  • 17
  • 1
    `arr.sort((a, b) => b.timestamp - a.timestamp || a.name.localeCompare(b.name))`. Are there objects in the array with the same `timestamp` property? – adiga Apr 08 '21 at 14:55
  • The timestamp sorting works I just need both timestamp and name – ousmane784 Apr 08 '21 at 14:57
  • 1
    Using only one sort call (see dupe target) is the preferred solution. However, some side-notes on what you are saying: sorting is typically O(n*log(n)), not "just" a loop, but as long as you aren't doing this very often per second, 1000 elements isn't big. In modern JS, `Array.prototype.sort` is required to be stable, but that wasn't always the case: ["ECMAScript 2019 introduced \[...\] requiring that Array.prototype.sort be a stable sort"](https://tc39.es/ecma262/#sec-intro). For your plan to "add another sort function [in sequence]", you need a stable-sort. – ASDFGerte Apr 08 '21 at 15:03
  • 1
    @ousmane784 the `sort` in my comment with `||` answers that – adiga Apr 08 '21 at 15:18

0 Answers0