1

I'm trying to sort an array of objects by property. I can't find out where I'm making mistake, but it does not sort it at all. Could you please help me . Here check my sandbox : https://codesandbox.io/s/pedantic-villani-361wh

const data = [{
    key: 33049999926180,
    sn: 33049999926180
  },
  {
    key: 33050000960170,
    sn: 33050000960170
  },
  {
    key: 33050001827158,
    sn: 33050001827158
  },
  {
    key: 33050002745147,
    sn: 33050002745147
  },
  {
    key: 33052513640473,
    sn: 33052513640473
  }
];

const handleClick = (data) => {
  let temp = data;
  temp.sort((a, b) => (a.sn < b.sn ? -1 : a.sn > b.sn ? 1 : 0));
  console.log(temp); // check console
};
handleClick(data)
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Yerlan Yeszhanov
  • 2,149
  • 12
  • 37
  • 67
  • 1
    try to use `-` instead of `<` and `>`, something like: `((a,b) => {return a.sn - b.sn})` – Calvin Nunes Feb 21 '20 at 12:30
  • 2
    Your sort comparator is sorting in an ascending order, which your `sn` property is already ordered as such. Therefore no sorting takes place. – Terry Feb 21 '20 at 12:32
  • @CalvinNunes it works! could please explain why in my case I need to use "-" . here in other post https://stackoverflow.com/a/46848788/7234678 they are using < and > – Yerlan Yeszhanov Feb 21 '20 at 12:34
  • @YerlanYeszhanov read here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort, official documentation, there is some examples and explanations – Calvin Nunes Feb 21 '20 at 12:35
  • 2
    `a.sn - b.sn` sorts descendingly, which is opposite to what your code does ;) that's why it works. Also, it helps to mention in **which order/direction** you want the sorting to take place. – Terry Feb 21 '20 at 12:36
  • Could have also used: `temp.sort((a, b) => (a.sn < b.sn ? 1 : a.sn > b.sn ? -1 : 0));` if that helps to unserstand or `temp.sort((a, b) => (a.sn > b.sn ? -1 : a.sn < b.sn ? 1 : 0));` – Riscie Feb 21 '20 at 12:37

1 Answers1

0

The reason you should use - instead of < is documented on MDN

To compare numbers instead of strings, the compare function can simply subtract b from a

This should be sufficient:

const data = [
  {
    key: 33049999926180,
    sn: 33049999926180
  },
  {
    key: 33050000960170,
    sn: 33050000960170
  },
  {
    key: 33050001827158,
    sn: 33050001827158
  },
  {
    key: 33050002745147,
    sn: 33050002745147
  },
  {
    key: 33052513640473,
    sn: 33052513640473
  }
];

const handleClick = data => [...data].sort((a, b) => b.sn - a.sn);
const sortedData = handleClick(data);
console.log(sortedData);