Reputation: 1
I want to try to make my own function. I want to sort an array of characters in increasing order and return the occurrence count of each character as a compact number.
Example:
function numberRepresentation(arr) {
// arr is an array
// return a number
/*
ex. arr=[b,a,a,a,c,b,a]
after sorting array will look like arr=[a,a,a,a,b,b,c]
occurrence of characters -> a = 4, b = 2, c = 1
so output will be 421
*/
}
How can I do it?
Upvotes: -2
Views: 471
Reputation: 3656
function numberRepresentation(arr) {
return arr.reduce((counts, letter) => {
const code = letter.charCodeAt(0)
counts[code] = counts[code] + 1 || 1
return counts
}, []).join('')
}
Explanation:
We just count occurrence of every letter, but we use a simple Array and char codes as indexes. Thus we automatically get a list of counts of letters ordered alphabetically (because the char codes go in abc order). So all we need to do is concatenate all the counts and return.
Upvotes: 0