Function groceries()

Hey guys! I’ve been looking all over the forums and I haven’t been able to find some to the groceries function in the

JavaScript Practice: Arrays, Loops, Objects, Iterators"

  • “Practice intermediate JavaScript concepts with these 3 code challenges.”

… the most I have been able to do is loop through each value, but I get stuck around that point… I’m not necessarily asking for the answer or solution but maybe a direction for me to go, or maybe something can help me that I may be over looking. Thank you so much!

Hello! Could you post the instructions to the question, please? One good thing I find to do if I’m stuck is to write pseudo code. This is basically just instructions written out for you to do the task by hand(but make it sound codey if you can). Then, after that, it’s easier to turn pseudo code into real code.

1 Like

for sure! Thank you! I have a huge problem with thinking too far in the code and not taking it step by step…

1 Like

Do you have any initial thoughts on how to do it? Hint: You’d need to use a loop (of course). You may need to make use of the object.key syntax to get the value.

1 Like

Hey!
I tried groceries( ) and wrote like this, but ‘Check answer’ said it has some syntax error ,
I know my coding is not so elegant and already saw example answer coding (so elegant!) .
But, I wanna know which part is error in my code. Help me…!

const groceries = arr => {
  let newMap = [];
  let newText = '';
  for(i = 0; i < arr.length; i++){
  newMap.push(arr[i].item);
  }
  let lastTwoItems = `${newMap[newMap.length-2]} and ${newMap[newMap.length-1]}`

  if(newMap.length === 2){
    console.log(`${lastTwoItems}`);
  } else if (newMap.length === 1){
    console.log(`${newMap[0]}`);
  } else if (newMap.length > 2){
    newText = newMap[0];
   for(i = 1; i < arr.length-2; i++){
     newText = newText + ', ' + newMap[i];
    }
    console.log(`${newText}, ${lastTwoItems}`);
  }
  }


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

groceries( [{item: 'Bread'}, {item: 'Butter'}] );
// returns 'Bread and Butter'

groceries( [{item: 'Cheese Balls'}] );
// returns 'Cheese Balls'

2 Likes

It doesn’t seem like you’ve got a syntax error. Could you post a screenshot of this, please?

This is screenshot

I see. The way CC gives those warnings is very spurious. Try changing the console.log() to returns. It’s likely that CC wants you to return the values, rather than console.log the values.

2 Likes

Thanks for your help!
I tried again by changing console.log() to return … Its still saying syntax error.

I wrote something wrong?

I’m glad to hear my this coding seems almost working, although I’m newbie and my coding is not so excellent.
Actually, this is my first asking at forum!

Can you post a screenshot of the instructions, please?

(notice, n.er and nerk004268602263104 is same person. I changed Username recently.)

this is instructions

Hi Neutrino,

I too am stuck with this.

I get the concept is to loop through the values and to somehow separate the last item in the array (hence arr.length -1) somehow so it can be logged. Very stuck

Here’s my code

> function groceries (arr, item) {
> 
>   let fullGroc = ''
> 
>   for (let i = 0; i < arr.length - 1; i++) {
> 
>     fullGroc.push(arr[i])
>   
>   }
> 
>   return fullGroc
> 
> }

You’ll want to use a mixture of control flow (ifelse ifelse) and for loops. Depending on the length of the array of grocery items, you’ll need to change how you loop through and log.

Looks like you didn’t define “i” in your loop. I hope that helps.

1 Like

Thanks Neutrino, but I don’t get why the length of the array matters - surely what matters here is the position of each object/element of the array (as the last one should have ‘&’ before it

True. But there are two ways to approach this. The way involving logic is easier, but less efficient.

// Write function below
const groceries = function(arr) {
  let newArr = [];
  for (let i = 0; i <= arr.length-1; i++) {
    newArr.push(arr[i].item)
  }
  if (arr.length > 2) {
    let newArr2 = [];
    for (let j = 0; j <= newArr.length-3; j++) {
      newArr2.push(newArr[j]);
};
   return newArr2.join(', ') + `, ${newArr[newArr.length-2]} and ${newArr[newArr.length-1]}`;
  } else if (arr.length === 2) {
    return newArr.join(' and ');
  } else {
    return newArr.join(', ');
  };

};

console.log(groceries([{item: 'Lettuce'}, {item: 'Onions'}, {item: 'Tomatoes'}]));

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'

Sharing my working code. :slight_smile: So apparently, you need to console.log the function calls at the end and use return in your functions in order to get ‘Check Answer’ to work properly and validate your code instead of the other way around. Hope this was helpful.

1 Like

Here’s my solution code if anyones looking for other ways on how to solve it. I think it’s a decent way of doing it… :sweat_smile::v:

const groceries = (list) => {
  // create array of strings
  let stringArr = list.map(groc => {
    return groc.item;
  });

// if theres only 2 items then join them with an ' and '
  if (stringArr.length < 3) {
    return stringArr.join(' and ');
  } else {
    // if theres more than two, join them with ', ' then seperate the last 2 items and join them with an ' and '
    let listedItems = stringArr.slice(0, stringArr.length - 2);
    let lastItems = stringArr.slice(-2);
    const combined = `${listedItems.join(', ')}, ${lastItems.join(' and ')}`;
    return combined;
  };
};
4 Likes

Hey everyone, just wanted to chime in on this post. My code console logged the correct answer, but I too was given a syntax error. What worked for me was the “Looks like you didn’t define “i” in your loop. I hope that helps.”

So basically, I wrote var in my for loop and it worked. :crazy_face:

1 Like

// Write function below

function groceries(arr){
  let arrMap = arr.map(val => val.item)
  if(arrMap.length > 1){
    arrMap.splice(arrMap.length-1, 0, "and")
  }
  let indexToSplit = arrMap.indexOf('and');
  let firstStr = arrMap.slice(0, indexToSplit).join(", ");
  let secondStr = arrMap.slice(indexToSplit).join(' ');
  if(firstStr.length < 1){
    return secondStr
  }else{
    return firstStr + " " + secondStr;
  }

}

I like the way you did it. What i did is to store the values of the array of object in an array using map, add the string “and” before the last string of the array. Then split the array in 2 by using the index of the string “and” as reference. Lastly I concatenate the two strings.