Stuck on the last bit of this challenge, the: " Write a function groceries()

Hi there!

I’m stuck on the last bit of this challenge, the: " Write a function groceries() that takes an array of object literals of grocery items".

I’m trying to solve it using “switch”.

My code so far returns an empty array, and I can’t spot why, could anyone please help?

const groceries = (obj) => {
    let newObj = [];
    let objByComas = obj.length-1;
  for (let i=0; i <=objByComas; i++){
    switch (obj){
    case (objByComas === 0): 
    return newObj.push(obj);
    case (objByComas === 1): 
    return newObj.push(`${obj[1,1]} and ${obj[2,2]}`);
    case (obj.length > 2): 
    newObj.push(obj.join(',') +  `and ${obj[obj.length]}`);
    return newObj;

Thanks so much!

What does the obj look like that is passed into the function?

What is the simplest use of a loop that can be implemented to construct the array from the object?


There is no reason to have return in the switch, it terminates loop and the function with an invalid return value… The length of the newObj array. How useful is that?

1 Like

and case (objByComas === 0):
should be case 0:

Otherwise it’ll just read (objByComas === 0) as true or false instead of as 0

    switch (objByComas) {
      case 0: 
      case 1: 
        newObj.push(`${obj[1,1]} and ${obj[2,2]}`);
        newObj.push(obj.join(',') +  `and ${obj[obj.length]}`);

return is not needed in the switch statement, since you’re trying to push stuff to an array and return it later, instead of ending the function inside the switch statement.

1 Like

Hi @mtf & @janbazant1107978602 thanks so much for the help!

@mtf => I’ll think about your questions and come back with solid answers– which I guess would mean that I’d solve the problem.