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
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 arrayis that callback nescessary?
yes, otherwise [5, 10, 2, 20] will be sorted as [10,2,20,5] (compared as string)
k fair
also, OP is sorting an array of objects by key
ooh ya, when u do a-b it converts the type
so works for mixture of number and string
for string you would like to do localeCompare in a callback
wai what's a local compare
lemme look up
damn
didn't know about this method
it's quite cool