I’m struggle to get array to sort the order but need to put null on top first then descend order for eg
var test = ["1998", "2005", null, "2015", "2022"];
I would like expect it to order in [null, "2022", "2015", "2005", "1998"]
;
What I’ve tried.
test.sort(function(a, b) {
return (
(b === null) - (a === null) ||
("" + b).localeCompare(a)
);
});
the problem is I’m using typescript, as there was error:
The left-hand side of an arithmetic operation must be of type any
, number
, bigInt
or an enum
type.
The right-hand side of an arithmetic operation must be of type any
, number
, bigInt
or an enum
type.
How do I resolve the issue?
6
Answers
This Has solved the problem. Thank you. By the way you can change null to "" if there is blank space just in case.
Instead of subtracting booleans, you can explicitly write out the conditions.
Alternatively, you can use the unary plus operator to coerce to a number.
You can use
sort()
then follow byreverse()
as followwhich produces
The TypeScript error
The reason you get these errors is your attempt to subtract
boolean
byboolean
which is invalid:You must convert
boolean
to apply the operation. i.e. turn it into one ofany
,number
,bigInt
, orenum
.Sort
In this case, a
boolean
is converted to0 | 1
by JavaScript. So, do it explicitly in TypeScript.After this, you may still see an error:
This is because the variable
a
has a typestring | null
butlocaleCompare
need astring
. In another word,("" + b).localeCompare(a)
only make scene if botha
andb
are of typestring
(in TypeScript). So just separate thenull
check:You could sort
null
to top and the rest by value.You can use
localeCompare
and with ternary operator for shorter syntax