JavaScript Code challenge groceries()

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.

So this was the challenge. I answered the challenge and it provided me with the right answers when I run the code yet it keeps telling me I have an error. I am unsure of what I am doing wrong if when I run the examples it gives me the correct responses. Anyone know why?? below is my code.

function groceries(arr) {
//remove the values that I want to use within the array of objects
  arr1 = arr.map(a => a.item);
//determine the array length so I can splice in the 'and' if needed
  arrlength = arr1.length - 1;
//condition to determine if the splice of 'and' is needed
  if (arrlength > 0) {
//use of splice to put in 'and'
  arr1.splice(arrlength, 0, 'and');
//join array into a string with spaces
  arr1 = arr1.join(' ');
  } else {
//other part of condition if the 'and' is not required which will create the string desired
  arr1 = arr1.join(' ');
  }
// return the string 
  return arr1
  };
// Write function below function groceries(arr) { arr1 = arr.map(a => a.item); arrlength = arr1.length - 1; if (arrlength > 0) { arr1.splice(arrlength, 0, 'and'); arr1 = arr1.join(' '); } else { arr1 = arr1.join(' '); } return arr1 }; console.log(groceries( [{item: 'Carrots'}, {item: 'Hummus'}, {item: 'Pesto'}, {item: 'Rigatoni'}] )); // returns 'Carrots, Hummus, Pesto and Rigatoni' console.log(groceries( [{item: 'Bread'}, {item: 'Butter'}] )); // returns 'Bread and Butter' console.log(groceries( [{item: 'Cheese Balls'}] )); // returns 'Cheese Balls'

Actually each item is only separated by a space, not a comma! That might be why you’re getting an error :smile:

Let me try that. In the display it does not show a comma for the response