简体   繁体   中英

What is the smallest change in the following code snippet so that the output is “ABC”?

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

  • apply concat() on acc not with x
  • Set initial value of acc to '' by passing it as second parameter of reduce()
  • You can use + 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.

  • it should be acc.concat(x.toUpperCase())
  • You missed 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM