简体   繁体   中英

Javascript _.reduce() exercise

Please help; I'm trying to solve this problem:

Write a function that takes an array of names and congratulates them. Make sure to use _.reduce as part of the function.

input:

['Steve', 'Sally', 'George', 'Gina']

output:

'Congratulations Steve, Sally, George, Gina!'

Here's what I have so far, but doesn't work:

var myArray = _.reduce(['Steve', 'Sally', 'George', 'Gina'], function(current, end) {
return 'Congratulations' + current + end;
});

You could do it like this:

var myArray = 'Congratulations ' + _.reduce(['Steve', 'Sally', 'George', 'Gina'], function(current, end) {
    return current + ', ' + end;
});

// "Congratulations Steve, Sally, George, Gina"

But reduce is not the most convenient tool for this, simple join feels more natural:

'Congratulations ' + ['Steve', 'Sally', 'George', 'Gina'].join(', ');

This is my solution, that uses all the parameters of the reduce function.

var people = ["Steve", "Sally", "George", "Gina"];

people.reduce(
  function(prev, curr, currIndex, array){
    if(currIndex === array.length - 1){
      return prev + curr + "!";
    } else{
      return prev + curr + ", ";
    }
  }, "Congratulations ");
['Steve', 'Sally', 'George', 'Gina'].reduce(
    (a, b, i) => a + " " + b + (i <= this.length + 1 ? "," : "!"),
    "Congratulations"
)

Here you go a full reduce :

['Steve', 'Sally', 'George', 'Gina'].reduce( function(o,n, i, a){ var e=(i===(a.length-1))?"!":","; return o+n+e; }, "Congratulations ")

1) you have to use "Congratulations" as the first element reduce(f, initial) see mdn

2) you have two cases: a) the last element is not reached, so append "," b) else append "!". This is accomplished with the check of the current index to the length of the array i===(a.length-1)

// Input data
const names = ['Steve', 'Sally', 'George', 'Gina']

// Do the reduce
result = names.reduce((carry, name) => {
  return carry + " " + name
}, "Congratulations") + "!"

// Print-out the result
console.log(result)  // "Congratulations Steve Sally George Gina!"

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