It'll work in most cases, but it's unnecessarily computationally expensive.
It may not work when certain non-ASCII characters are used, because .split('')
will result in splitting up the character code points, eg:
console.log(''.split(''));
That's not an accurate representation of each character as an element of the array. Use Array.from
instead:
console.log(Array.from(''));
After that, you can also make the algorithm less expensive by counting up the number of occurrences of each character (O(n)
) rather than sorting (O(n log n)
). For example:
const getCount = str => Array.from(str).reduce((counts, char) => {
counts[char] = (counts[char] || 0) + 1;
return counts;
}, {});
function same(ar,ar1){
const counts1 = getCount(ar);
const counts2 = getCount(ar1);
const keys1 = Object.keys(counts1);
const keys2 = Object.keys(counts2);
if (keys1.length !== keys2.length) {
return false;
}
return keys1.every(char => counts1[char] === counts2[char]);
}
console.log(same('abc', 'cba'));
console.log(same('abc', 'aba'));