how would I sort this using .sort() function in javascript? I know I can add a comparison function here but I'm not sure how I would program this.
Before
1 024c
100 000c
143c
1 020c
10 000c
After
143c
1 020c
1 024c
10 000c
100 000c
how would I sort this using .sort() function in javascript? I know I can add a comparison function here but I'm not sure how I would program this.
Before
1 024c
100 000c
143c
1 020c
10 000c
After
143c
1 020c
1 024c
10 000c
100 000c
If your input is an array then you can use a comparator function
(a,b) => a.replace(/[^\d.]/g, "") - b.replace(/[^\d.]/g, "")
this will remove c and space from the string to form number and compare. See the code below.
var data = ["1 024c",
"100 000c",
"143c",
"1 020c",
"10 000c"]
var sorted = data.sort( (a,b) => a.replace(/[^\d.]/g, "") - b.replace(/[^\d.]/g, ""));
console.log(sorted);
/ |c/g with either /\D/g or /[^\d.]/g. The first one keeps only digits. The second keeps only digits and decimals.It seems like you want to sort it based on the numbers in them, while excluding spaces.
x.sort(
(eachObj, prevObj) =>
parseInt(eachObj.replace(" ","")) - parseInt(prevObj.replace(" ",""))
);
In ES6
["143c", "1020c", "1024c", "10000c", "100000c"], which is not what's wanted. You need to retain the spaces after sort.