Code challenge in Intermediate JS practice

In the last code challenge here, the groceries() function takes an array of objects and returns a string with items separated by comma, except the last one which should be the word ‘end’.

So, my code (below) is nowhere as neat and short as the solution (which I won’t post here), but seems to work as expected. But, it still doesn’t pass the test. Is there anything that I’ve missed, or is it just down to how they test the code? Thanks for all the suggestions!

function groceries(array) {

  let arrayLength = array.length;

  const newArray = array.map( (element) => {

    return element.item + ', ';
  } );

  newArray[arrayLength - 1] = newArray[arrayLength - 1].replace(', ', '');

  newArray[arrayLength - 2] = newArray[arrayLength - 2].replace(', ', ' and ');

  return newArray.join('');

}
console.log(groceries( [{item: 'Carrots'}, {item: 'Hummus'}, {item: 'Pesto'}, {item: 'Rigatoni'}] ));
// returns
// Carrots, Hummus, Pesto and Rigatoni

I think this may fail when the array has only 1 element.

1 Like

Of course it does, thanks for pointing out!