Created
October 14, 2021 22:31
-
-
Save RahimGuerfi/f5f31db6f70d1808fab2966ca786149d to your computer and use it in GitHub Desktop.
Codecademy - JavaScript Practice: Arrays, Loops, Objects, Iterators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Write a 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. | |
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' | |
*/ | |
// Write function below | |
const groceries = arr => { | |
const len = arr.length; | |
if (len == 1) | |
return arr[0].item; | |
else if (len == 2) | |
return arr[0].item + ' and ' + arr[1].item; | |
let str = ''; | |
arr.forEach((obj, indx) => { | |
if (indx + 1 == len) | |
str += `and ${obj.item}`; | |
else if (indx + 2 == len) | |
str += `${obj.item} `; | |
else | |
str += `${obj.item}, `; | |
}) | |
return str; | |
} | |
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' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment