Can't push() to a string in a practice challenge

Hey, can someone please hint at what is wrong with this code? I’m trying to add ‘,’ to the end of every word in an array, but for some reason it doesn’t work.

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.

const groceries= (arr) => {
  const newArray = => {
    return object.item; //array of items 
  //won't add , for last 2 elements
  for (let i = 0; i < newArray.length - 2; i++) {
  console.log(newArray); //Why are ',' not showing?
  let sentence = newArray.join(' ');

groceries( [{item: 'Bread'}, {item: 'Butter'}] );```

I tried to do the same thing with for (let word of newArray) loop, doesn’t work either

for (let word of newArray) {

We don’t need to alter that string data in the array. When we join the data, we use ", " as the separator string.

Huh, didn’t think about that, thanks.

But I’d still love to know why the code doesn’t work, so that I keep that in mind for future projects.

1 Like

newArry[i] is not an Array object, so has no push attribute.

You could use concatenation…

newArray[i] += ","

The function request was to return a string, not an array. But, given the desire to return a new array, your example isn’t doing anything because it only has two items in the array, and you are subtracting 2 from newArray.Length, so your for loop isn’t doing anything for this example. (i = 0; i < (2 - 2); i++) since i already exceeds the condition of i < 0, the loop is never entered.

If extra items are added to the list passed into groceries, an error appears on the attempt to push.
~newArray[i]~ is an element of the array so the push function is not applicable at that point.

you could do ~newArray[i] += ‘,’ - but you could also do this in your map, but you still need to add that “and” between the last two items

string = "";

for (let i = 0; i < arr.length; i++){

  // if i is 0, add the item to string
// if i > 0 and < length - 1 add a  ", "  then add the item
//  if i > 0 and = length - 1 add "and " and the item