Intermediate Javascript Practice: function groceries()

I’m so stuck with this exercise. Can someone help and tell my what i did wrong?
Your help is highly appreciated

thanx

I used .join(', ') instead of .toString() for firstPart

1 Like

Your code outputs this: ' Carrots, Hummus, Pesto and Rigatoni'. Notice there is an extra space out the front, you can remove this using String.prototype.trim;:

const groceries = (arr) => {
	const newArr = [];
	arr.forEach(item => newArr.push(" " + item.item));
	if (newArr.length > 1) {
		const firstPart = newArr.slice(0, -1).toString();
		const lastElement = newArr[newArr.length - 1].toString();
		return firstPart + " and" + lastElement;
	} else {
		return newArr.toString().trim();
	}
};

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

Which will remove that extra space.

1 Like

Matt, thanks alot for looking @ my code :pray:

1 Like