1

I have an array of characters (arr) and a string (J), I wanted to use the array.reduce() method to count the number of characters of the array (arr) present in the string J.

Below is the code which shows how I am using array.reduce() method,

let val = arr.reduce((count , ch) => {
    return J.includes(ch) ? count + 1 : count
});

But when I tried with sample value as,

arr = ​​​​​[ 'a', 'A', 'A', 'S', 'S' ]​​​​​;

J = 'aA';

I get the anser as

val = 'a11'

1 Answer 1

6

You need to add initialValue in second parameter of .reduce() as mentioned in docs

arr.reduce(callback[, initialValue])

var arr = [ 'a', 'A', 'A', 'S', 'S' ];
var J = 'aA';
let val = arr.reduce((count , ch) => {
    return J.includes(ch) ? count + 1 : count
}, 0);
console.log(val);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.