Skip to content Skip to sidebar Skip to footer

Javascript Es6 Custom Sort Method Not Working All The Times

I want to sort my JSON output. I made my own sort method for it as you can see here: const sortAsc = (propertyName) => (a, b) => a[propertyName] === b[propertyName] ? 0 : a[p

Solution 1:

You could use String#localeCompare with option:

The localeCompare() method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.

The new locales and options arguments let applications specify the language whose sort order should be used and customize the behavior of the function. In older implementations, which ignore the locales and options arguments, the locale and sort order used are entirely implementation dependent.

constsortAsc = propertyName => (a, b) =>
    a[propertyName].localeCompare(b[propertyName], undefined, { numeric: true, sensitivity: 'base' });


constsortDesc = (propertyName) => (a, b) =>
    -a[propertyName].localeCompare(b[propertyName], undefined, { numeric: true, sensitivity: 'base' });

Solution 2:

I guess you want to compare Ids as numbers, so you should use appropriate sorting functions for number-like columns:

constsortAsc = (propertyName) => (a, b) => a[propertyName] === b[propertyName] ? 0 : +a[propertyName] < +b[propertyName] ? -1 : 1;
constsortDesc = (propertyName) => (a, b) => a[propertyName] === b[propertyName] ? 0 : +a[propertyName] < +b[propertyName] ? 1 : -1;

Another way is to adjust you table data array, ids should be numbers there, not strings, in this case your sorting functions should also work.

Solution 3:

Your comparison functions are totally fine. The relational operators work out of the box on both numbers and strings, there's no reason to use localeCompare.

It works sort of but when I sort it it doesn't sort right always: it doesn't really work with the ID.

It appears that the id properties in your array of objects are strings, so they are compared lexicographically. Make them actual numbers and they'll be compared as numbers.

It works ascending on Naam But when descending it first gives 2 names starting with v & k. Why is that?

It's really hard to see in the gif, but it appears that those two weirdly sorted values begin with a space - which is always sorted first. Make sure your data is valid.

Post a Comment for "Javascript Es6 Custom Sort Method Not Working All The Times"