Taken from LeetCode
Given two strings
s
andt
, returntrue
ift
is an anagram ofs
, andfalse
otherwise.
Solution
This is the answer I came up with:
function isAnagram(s: string, t: string): boolean {
// An anagram isn't possible if the lengths differ
if (s.length !== t.length) { return false }
// Convert strings to sorted arrays
let _s = [...s].sort()
let _t = [...t].sort()
// Stringify the arrays and compare them
return JSON.stringify(_s) === JSON.stringify(_t)
}