-1

I was just trying to see how I can sort the items from newest to oldest in an object based on the dateModified prop.

I have tried doing the good old fashion way of sorting, however, the items still render in the same order no matter what. Is there any other way to do so other than this way?

Object:

enter image description here

Code:

const filteredAndSortedBotConfigs = Object.keys(botConfigs)
  .sort((a, b) => new Date(b.modifiedTimestamp) - new Date(a.modifiedTimestamp))
  .filter(this.filterConfigsByBot)
  .filter(
    (key) =>
      botConfigs[key].status === "RUNNING" && botConfigs[key].mode !== null
  );
Ajeet Shah
  • 12,593
  • 7
  • 43
  • 60
  • Can you share more details about the problem and share a JSON example of your object maybe? – Hassen Ch. Apr 07 '21 at 00:18
  • While this might seem like a silly idea, are you 100% sure you're using the order of that array and not, say, doing `Object.keys(botConfigs)` again? The code above looks correct. – DemiPixel Apr 07 '21 at 00:25

2 Answers2

0

Sort by date is simple:

arr.sort((a, b) => new Date(a) - new Date(b));
// Or
arr.sort((a, b) => new Date(a).getTime() - new Date(b).getTime());

In your code, a and b are keys (properties).

So, you need to use botConfigs[key].modifiedTimestamp to read the timestamp:

const filteredAndSortedBotConfigs = Object.keys(botConfigs)
  .sort(
    (a, b) =>
      new Date(botConfigs[a].modifiedTimestamp) -
      new Date(botConfigs[b].modifiedTimestamp)
  )
  .filter(this.filterConfigsByBot)
  .filter(
    (key) =>
      botConfigs[key].status === "RUNNING" && botConfigs[key].mode !== null
  );

Edit:

You are looking for "newest to oldest" i.e. descending order, so you just need to reverse the sign.

  • a - b will sort in ascending order
  • b - a will sort in descending order
Ajeet Shah
  • 12,593
  • 7
  • 43
  • 60
0

The date sorting logic is referencing the modifiedTimestamp property of the keys which are strings instead of the bot config objects (a.modifiedTimestamp and b.modifiedTimestamp are both undefined). Even after fixing it, you would only get the sorted keys and you have to use Array.prototype.map to get the sorted array of configs which I imagine is what you want.

You can use Object.values to get an array of configs, apply the filters and then sort them by the modifiedTimestamp property.

const filteredAndSortedBotConfigs = Object.values(botConfigs)
  .filter(this.filterConfigsByBot)
  .filter((config) => config.status === 'RUNNING' && config.mode !== null)
  .sort((a, b) => new Date(b.modifiedTimestamp) - new Date(a.modifiedTimestamp))

You should also update this.filterConfigsByBot since it receives the bot config object and not the key anymore.

filterConfigsByBot = (config) => {
  const { botId } = config
  // return a boolean based on the `botId` value
}
Arun Kumar Mohan
  • 9,934
  • 3
  • 16
  • 37