I have the following code for trying to get the total sum of the charCodes of one word. (Why I need that isn't important for my question)
function codepoints(string) {
return string.split("").reduce((arr, next) => arr.charCodeAt(0) + next.charCodeAt(0))
}
console.log(codepoints("abc"));
But JavaScript is giving me the error:
arr.charCodeAt is not a function
When asking the type of 'arr', it is a string. But why I can not use the method charCodeAt on it?
You are making two mistakes.
charCodeAt on array its Number(sum of char codes). 0 as second argument to reduce() which will be the initial value of arrfunction codepoints(string) {
return string.split('').reduce( (arr,next) => arr + next.charCodeAt(0),0)
}
console.log(codepoints("abc"));
Note: the variable name arr is not correct for situation. Use sum or ac or something like that.
You are not using Array.reduce correctly, the first parameter of the callback is the partial result or accumulator.
The Array.reduce takes a callback function which itself takes four more parameters, in your case you need the first two.
The syntax of the reduce function is reduce(callback[, initialValue]):
callback Function to execute on each element in the array, taking four arguments:
accumulator The accumulator accumulates the callback's return values; it is the accumulated value previously returned in the last invocation of the callback, or initialValue, if supplied (see below).
currentValue The current element being processed in the array.**
initialValue Optional Value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used. Calling reduce() on an empty array without an initial value is an error.
To find the sum pass an initial value of 0 and then the add the subsequent elements in the array to it:
function codepoints(string) {
return string.split('').reduce( (acc,next) => acc + next.charCodeAt(0), 0)
}
console.log(codepoints("abc"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With