Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function list(names){
- if(names.length == 0) return "";
- if(names.length == 1) return names[0].name;
- var arr = []
- // names.forEach(function(x){
- // arr.push(x.name + ", ")
- // })
- for(let i = 0; i<names.length-2; i++){
- arr.push(names[i].name + ", ")
- }
- arr.push(names[names.length - 2].name)
- arr.push(names[names.length - 1].name)
- if(arr.length > 1){
- arr[arr.length - 1 ] = " & " + arr[arr.length - 1 ]
- }
- return arr.join("");
- }
- function bestList(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;
- }
- }, '');
- }
- list([{name: 'Bart'},{name: 'Lisa'},{name: 'Maggie'},{name: 'Homer'},{name: 'Marge'}])
Add Comment
Please, Sign In to add comment