Issue
I have an array of strings representing numbers, and I want to be able to see how many times a certain string repeats on my array:
const numbers = ['1', '2', '3', '4', '6', '2', '9', '5', '2'. '4', '8'];
const searchForValue = '2';
const timesAppeared = numbers.reduce(
(previousValue, currentValue) => previousValue + (currentValue === searchForValue),
0
);
However, the operation inside my reduce function gives me the following error:
Operator '+' cannot be applied to types 'number' and 'boolean'.
How can I tackle this?
Solution
Trying to keep the code relatively the same, just added the Number cast/constructor.
const numbers = ['1', '2', '3', '4', '6', '2', '9', '5', '2', '4', '8'];
const searchForValue = '2';
const timesAppeared = numbers.reduce(
(previousValue, currentValue) => previousValue + Number(currentValue === searchForValue),
0
);
Typescript loves type consistency! Before your code was trying to add a boolean result to a number which isn't possible (e.g. 1 + false). All we did here was convert that boolean result to a number. However I would recommend learning how the ternary operation in Alexander Mills' answer works.
Answered By - knary
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.