JavaScript Practice: Arrays, Loops, Objects, Iterators

Hello all.

Below is my solution to the third challenge in the " Arrays, Loops, Objects, Iterators" section of the JavaScript course. It passes the checks, but I can’t help feeling it is inelegant. I’d be grateful for any feedback on more concise/readable solutions. :slightly_smiling_face:

const groceries = groceryList => {

    let groceryString = '';
    let groceryArray = [];
    
    groceryList.forEach(object => groceryArray.push(object.item));

    for (let i = groceryArray.length - 1; i >= 0; i--) {
        if (i === groceryArray.length - 1) {
            groceryString = groceryArray[i];
        } else {
            if (i === groceryArray.length - 2) {
                groceryString = groceryArray[i] + ' and ' + groceryString;
            } else {
                groceryString = groceryArray[i] + ', ' + groceryString;
            }
        }
    }

    return(groceryString);

};

Can you provide a link to the lesson, please?

You could already simplify your code by moving the first two conditions out of the for loop. Initialize groceryString with the last two items of the groceryArray and start the loop at groceryArray.length - 3. Then you won’t need a conditional statement in your for loop at all.

Thank you for your feedback. Link to the lesson follows: https://www.codecademy.com/journeys/full-stack-engineer/paths/fscj-22-building-interactive-websites/tracks/fscp-22-javascript-syntax-part-ii-c8ddbace-1463-4797-ae12-503c7b0f9552/modules/wdcp-22-practice-javascript-syntax-arrays-loops-objects-iterators-1214fbf4-8717-4c43-9940-b6599d0f1fb7/articles/fecp-javascript-practice-arrays-loops-objects-iterators

The reason I put the three cases in the loop was I was not sure what the length of the array of objects passed would be, so I was testing for cases of one, two or more elements.

Ok that makes sense. But I think it would still be simpler if you did the test outside of the loop, because then you could leave before you already did unnecessary logic and have less nested code:

if (groceryList.length < 1) return ''
let groceryString = groceryList[groceryList.length-1].item
if(groceryList.length === 1) return groceryString

Another approach you could try would be the .reduce() method.

1 Like