Check if two strings are anagrams
Compare the sorted, lowercased characters of both strings.
function areAnagram({ first, second }) { const sorted = text => Array.from(text.toLowerCase()).sort().join(''); return sorted(first) === sorted(second); }
Input & expected output
Input
{
"first": "Listen",
"second": "Silent"
}Expected output
trueThe edge case
Input
{
"first": "dormitory",
"second": "dirty room"
}Expected output
falseKnow the limits
- Spaces and punctuation count, as the edge case shows; strip them first for phrase anagrams.
- Sorting is by code point, so accented letters are distinct from their base letters.
The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.
Source & maintenance
Based on Check if two strings are anagram from the original 1loc collection by Nguyen Huu Phuoc, with mahdiyar. Copyright (c) 2020 phuoc-ng. MIT licensed.
Iterates code points and takes both strings as one object input. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Capitalize a string — Uppercase the first Unicode code point and preserve the remaining text.
- Reverse a string — Reverse Unicode code points without splitting surrogate pairs.
- Check a palindrome — Compare a string with its code-point reversal.