My solution to convert array of object literals into string works but is not computer disagrees

Hi All,

I’m doing the 3rd code exercise of JavaScript Practice: Arrays, Loops, Objects, Iterators

I’ve tested the output and it’s correct but when I click check answer it states:
Tested groceries([{item: 'Lettuce'}, {item: 'Onions'}, {item: 'Tomatoes'}]) and it did not return 'Lettuce, Onions and Tomatoes' .

I thought the code you create doesn’t exactly have to match the solution so what am I missing?
Granted my solution is not very elegant but it still produces the correct output (see below).

// Write function below //log conversion array of object literals to string const groceries = arr => { const str = arr.reduce((acc, curVal) => `${acc}${curVal.item}, `, ''); //console.log(str); const lastIndex = str.lastIndexOf(',') const replacement = "'"; const replaced = str.substring(0, lastIndex) + replacement + str.substring(lastIndex + 1); const withAnd = replaced.replace(/,(?=[^,]*$)/, ' and'); //console.log(withAnd); const final = "'" + withAnd; return final; }

fyi I did pass groceries([{item: ‘Lettuce’}, {item: ‘Onions’}, {item: ‘Tomatoes’}]) into the bottom of my code and tinkered around with this many times, driving myself mad in the process.

You have an extra ' at the beginning and end of the string that’s returned.
Change two lines to take that out:
Those should be

const replacement = "";

and

const final = "" + withAnd;

And it looks like you have an extra space at the end of the string that’s returned.
You can fix that by changing the return to be

return final.slice(0, -1);

so that the last character in the string is taken out.

2 Likes

Thank you that worked.

I realise now that I was thinking I needed to add in the quotation marks at the start and end of the string because of the example at the top of the exercise; BIG FAT :man_facepalming:t4: