0

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 
4
  • 2
    What is format in which you are getting this input? On what basis are you sorting this? What have you tried? Commented Feb 21, 2018 at 18:24
  • 1
    Can you show your first implementation. Commented Feb 21, 2018 at 18:26
  • @void I am trying to order a table column which text similar to this. I have tried the very basic return a-b which works for columns which only has text Commented Feb 21, 2018 at 18:32
  • @confusedOne see my answer below. Commented Feb 21, 2018 at 18:33

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

2 Comments

This looks good, but you might want to replace / |c/g with either /\D/g or /[^\d.]/g. The first one keeps only digits. The second keeps only digits and decimals.
@ScottSauyet makes sense. Edited :)
0

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

2 Comments

Note that this gives back ["143c", "1020c", "1024c", "10000c", "100000c"], which is not what's wanted. You need to retain the spaces after sort.
@ScottSauyet missed that. Edited. Thx.