-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFormatAStringOfNames.js
More file actions
35 lines (30 loc) · 896 Bytes
/
FormatAStringOfNames.js
File metadata and controls
35 lines (30 loc) · 896 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
function list(names) {
let newNames = names.reduce((array, item, index) => {
if (names.length === 1) array.push(item.name)
else if (index === names.length - 1 && index) array.push(item.name)
else if (index === names.length - 2) array.push(item.name + ' &')
else array.push(item.name + ',')
return array
}, []);
return newNames.join(' ')
}
// Best Practices Solution from CodeWars:
function list(names) {
return names.reduce(function (prev, current, index, array) {
if (index === 0) {
return current.name;
}
else if (index === array.length - 1) {
return prev + ' & ' + current.name;
}
else {
return prev + ', ' + current.name;
}
}, '');
}
// Voted Most Clever Solution from CodeWars:
function list(names) {
var xs = names.map(p => p.name)
var x = xs.pop()
return xs.length ? xs.join(", ") + " & " + x : x || ""
}