Reputation: 451
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;
});
Upvotes: 1
Views: 609
Reputation: 417
// 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!"
Upvotes: 0
Reputation: 75
['Steve', 'Sally', 'George', 'Gina'].reduce(
(a, b, i) => a + " " + b + (i <= this.length + 1 ? "," : "!"),
"Congratulations"
)
Upvotes: 1
Reputation: 19
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 ");
Upvotes: 1
Reputation: 5676
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)
Upvotes: 0
Reputation: 193261
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(', ');
Upvotes: 3