Varun Sukheja
Varun Sukheja

Reputation: 6526

Use array.reduce() for array of characters

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'

Upvotes: 1

Views: 1087

Answers (1)

Mohammad
Mohammad

Reputation: 21489

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);

Upvotes: 6

Related Questions