0

I have a sort function that orders items with the class '.sortbox', finds the '.num' value and sorts using flex order. This works fine, but some of the values have extra characters (./-) and this breaks it.

How can I search but ignore all characters that are not numbers?

My attempt here: If I have it all completely wrong then appreciate help to understand why.

https://jsfiddle.net/9cwyund6/1/

function sorting(){
  var items = document.querySelectorAll('.sortbox')
  Array.from(items).sort(function(a, b) {
    a = ~~a.querySelector('.num').innerText
    b = ~~b.querySelector('.num').innerText
    return a - b
  }).forEach(function(n, i) {
    n.style.order = i
  })
}
  • That sort is going to have the worst performance ever. Give example HTML that is causing you issues. – epascarello Jun 15 '22 at 11:37
  • You can use a [RegEx](https://stackoverflow.com/questions/1862130/strip-all-non-numeric-characters-from-string-in-javascript) in your `sort` function. – bryce Jun 15 '22 at 11:37
  • You can use isNan function to check if it is a number or not. – raj240 Jun 15 '22 at 11:41
  • So -13 is higher than 3? Or even 1.3? I.e Are you sure you want to ignore these characters or do you want to parse them correctly? – Kaiido Jun 15 '22 at 11:54
  • This is probably my very bad attempt I agree. It is a date that is pulled in from a json file... If I ignore all characters I get the desired result. – user1612249 Jun 15 '22 at 12:04
  • https://jsfiddle.net/9cwyund6/1/ – user1612249 Jun 15 '22 at 12:05

2 Answers2

0

You could strip the strings a and b from all non digit characters while sorting

return a.replace(/\D/g,'') - b.replace(/\D/g,'')
Nestoro
  • 787
  • 6
  • 17
0

You can use

isNaN() 

method to check if something is a number or not.

raj240
  • 646
  • 7
  • 17