-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGroceriesArray.js
33 lines (23 loc) · 941 Bytes
/
GroceriesArray.js
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
/* function groceries() that takes an array of object literals of grocery items.
The function should return a string with each item separated by a comma except the last
two items should be separated by the word 'and'. Make sure spaces (' ') are inserted where they are appropriate.
*/
const groceries = list => {
let listString = ''
for (let i=0; i<list.length; i++) {
listString += list[i].item;
if (i < list.length - 2) {
listString += ', ';
} else if (i == list.length - 2){
listString += ' and ';
}
}
// return listString;
console.log(listString);
}
groceries( [{item: 'Carrots'}, {item: 'Hummus'}, {item: 'Pesto'}, {item: 'Rigatoni'}] );
// returns 'Carrots, Hummus, Pesto and Rigatoni'
groceries( [{item: 'Bread'}, {item: 'Butter'}] );
// returns 'Bread and Butter'
groceries( [{item: 'Cheese Balls'}] );
// returns 'Cheese Balls'