Groceries function from JS practice: arrays, loops, objects, iterators

THE CODE DOWN BELOW IS A FINAL SOLUTION FROM CODECADEMY. I JUST NEED TO UNDERSTAND HOW IT WORKS.

Hello everyone, I’m having a hard time understanding this code from the practice. Can you please explain how this code works. Specifically, the IF ELSE part where the index is 0 and list length is 3 - 2 which is 1. So the iteration added a comma after the first string and when the second iteration goes the index is 1 and list length is still 3 - 2 which is 1 from here it goes to ELSE IF statement because previous one came out as FALSE. Here index is 1 and list length is still 3 - 2 is 1 that means it should add “AND” instead of ", ". I’m stuck on this part. (It would be great for CODECADEMY developers to include comment on their solutions for us students to understand their code)

Here is the instruction: 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 = list => {
  let listString = ''

  for (let i=0; i<list.length; i++) {
    listString += list[i].item;
    if (i < list.length - 2) {
      listString += ', ';
    } else if (i == list.length - 2){
      listString += ' and ';
    }
  }
  
  return listString;
}

groceries( [{item: 'Carrots'}, 
                   {item: 'Hummus'}, 
                   {item: 'Pesto'}, 
                   {item: 'Rigatoni'}] );

Not sure that is helping, eh?

sorry its a typo. lol

First question to ask is, are we mutating the array or in need of the index? In many cases neither, which is the case here. If all we want is access to the data, without a care for where it sits, then access the data points with of.

Here is the instruction: 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.

Morning,
Remember, whilst the index starts at 0, the length will be the actual length (i.e. 4 in this case, not 3).

1 Like