Javascript - Sort by Number

as the title suggests, I'm trying to sort by number. This is sorting by string? Any ideas?
if (order == "desc"){ e.target.setAttribute("data-order", "asc"); tableData = tableData.sort((a,b) => a[column] > b[column] ? 1: -1) } else if (order == "asc"){ e.target.setAttribute("data-order", "desc"); tableData = tableData.sort((a,b) => a[column] < b[column] ? 1: -1) }
9 Replies
glutonium
glutonium2mo ago
are you trying to sort an array of string or a number? is u have an array of number const a = [1,6,0,3,0,6,4,8] and u do a.toSorted() this will return a new array [ 0,0,1,3,4,6,6,8 ] if u have an array of string const b = ["abdj", "zndjdj", "dmxkx", "bjdid" ] and u do b.toSorted() this will return a new sorted array, sorted ased on the ascii value of the first character [ "abdj", "bjdid", "dmxkx", "zndjdj" ] btw u should use toSorted as it doesn't mutate the original array
MarkBoots
MarkBoots2mo ago
//asc
tableData.sort((a,b)=>a[column] - b[column]);

//des
tableData.sort((a,b)=>b[column] - a[column]);
//asc
tableData.sort((a,b)=>a[column] - b[column]);

//des
tableData.sort((a,b)=>b[column] - a[column]);
glutonium
glutonium2mo ago
is that callback nescessary?
MarkBoots
MarkBoots2mo ago
yes, otherwise [5, 10, 2, 20] will be sorted as [10,2,20,5] (compared as string)
glutonium
glutonium2mo ago
k fair
MarkBoots
MarkBoots2mo ago
also, OP is sorting an array of objects by key
glutonium
glutonium2mo ago
ooh ya, when u do a-b it converts the type so works for mixture of number and string
MarkBoots
MarkBoots2mo ago
for string you would like to do localeCompare in a callback
glutonium
glutonium2mo ago
wai what's a local compare lemme look up damn didn't know about this method it's quite cool