Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I can't use string.charCodeAt() at elements of reduce callback

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?

like image 473
Doddle Avatar asked Nov 21 '25 14:11

Doddle


2 Answers

You are making two mistakes.

  • You don't need to apply charCodeAt on array its Number(sum of char codes).
  • Also pass 0 as second argument to reduce() which will be the initial value of arr

function 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.

like image 61
Maheer Ali Avatar answered Nov 24 '25 04:11

Maheer Ali


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"));
like image 37
Fullstack Guy Avatar answered Nov 24 '25 05:11

Fullstack Guy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!