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)
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.