Hello I had this issue with my function
const string = ['a', 'b', 'c'].reduce((acc, x) => x.concat(x.toUpperCase()));
console.log(string );
And in the final result I want to get "ABC"
You need to do two things
concat()
on acc
not with x
acc
to ''
by passing it as second parameter of reduce()
+
instead of contat()
const string = ['a', 'b', 'c'].reduce((acc, x) => acc+x.toUpperCase(),''); console.log(string );
You can also do it using map()
and join()
const string = ['a', 'b', 'c'].map(x=>x.toUpperCase()).join('') console.log(string );
It looks like you want a string? join()
to a string and .toUpperCase()
is the direct and simple. Using reduce()
is overkill.
const string = ['a', 'b', 'c'].join('').toUpperCase(); console.log(string);
You are not using concat()
with the accumulator acc
string and also not passing the initial value of it which should be an empty string ""
(otherwise the first character of the resulting string would be lowercase as toUpperCase()
won't be applied to it).
Learn more about Array#reduce
, this function takes the accumulator as the first param and the elements of the array as a second param and two other optional params.
const string = ['a', 'b', 'c'].reduce((acc, x) => acc.concat(x.toUpperCase()), ""); console.log(string );
You have two misses.
acc.concat(x.toUpperCase())
initial value
in reudce. else it will not change the first
character to upper-case const string = ['a', 'b', 'c'].reduce((acc, x) => acc.concat(x.toUpperCase()),''); console.log(string );
On side note:- You can simply use +
instead of concat
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.