0

Can anybody solve this mystery for me?

I have an array of dictionaries which I want to sort based on id, increasingly, for example

[{id:1, answer:"hi"}, {id:2, answer:"yo"}]

The following works, but it's the reverse of what I need.

question.answers.sort((a, b) => b.id - a.id);

enter image description here

Logically I'd assume the opposite would work as well, but it doesn't.

question.answers.sort((a, b) => a.id - b.id);

enter image description here

SJ19
  • 1,933
  • 6
  • 35
  • 68
  • Hi! Please post code, error messages, data, markup, etc. **as text**, not as a *picture* of text. Why: http://meta.stackoverflow.com/q/285551/157247 Also, please update your question with a [mcve] demonstrating the problem, ideally a **runnable** one using Stack Snippets (the `[<>]` toolbar button). Stack Snippets support React, including JSX; [here's how to do one](http://meta.stackoverflow.com/questions/338537/). – T.J. Crowder Oct 31 '20 at 09:08
  • Your logic is correct, and the code you've shown will sort the array as you've described, so something *else* is going on in code you haven't identified and shared. You'll find it as part of the process of putting together a [mcve]. – T.J. Crowder Oct 31 '20 at 09:09
  • 1
    Logically, yes, I agree. Beware though that `Array.prototype.sort` does an in-place sort, meaning it mutates the original array. How are you logging this. Something else is effecting your result. Can you provide a [Minimal, Complete, and Reproducible](https://stackoverflow.com/help/minimal-reproducible-example) code example? – Drew Reese Oct 31 '20 at 09:09
  • The console logs the array, but its elements appear as they are **when you expand the array** in the console. It is asynchronous. To get the situation at the time the log is made, take a copy of the array or stringify it: `console.log(JSON.stringify(question.answers))`. – trincot Oct 31 '20 at 09:18
  • @trincot - The first picture shows descending order, which is what the first code block does. It would be *ascending* if it were the result of the second code block. But nevertheless, the fact it's asynchronous is important to flag up, yeah. – T.J. Crowder Oct 31 '20 at 09:20
  • 1
    SJ19 - The **best** way to know what's actually going on is to use the debugger built into your browser, set a breakpoint, and example the contents of the array after the `sort`. No point stumbling around in the dark with a `console.log` torch when you can *turn on the lights* with the debugger. – T.J. Crowder Oct 31 '20 at 09:22
  • Yes, you are right. The first image is the descending order. We actually don't see where the OP makes the log nor in which order the mutations to the array are made... whether there are multiple, or just one, ... – trincot Oct 31 '20 at 09:22
  • \* example => examine – T.J. Crowder Oct 31 '20 at 09:27

0 Answers0