Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join an array by commas and "and"

I want to convert the array ['one', 'two', 'three', 'four'] into one, two, three and four

Note that the first items have a comma, and but there is the word and between the second-last one and the last one.

The best solution I've come up with:

a.reduce( (res, v, i) => i === a.length - 2 ? res + v + ' and ' : res + v + ( i == a.length -1? '' : ', '), '' ) 

It's based on adding the commas at the end -- with the exception of the second-last one (a.length - 2) and with a way to avoid the last comma (a.length - 2).

SURELY there must be a better, neater, more intelligent way to do this?

It's a difficult topic to search on search engines because it contains the word "and"...

like image 377
Merc Avatar asked Dec 21 '18 04:12

Merc


People also ask

How do you join an array with spaces?

To convert an array to a string with spaces, call the join() method on the array, passing it a string containing a space as a parameter - arr. join(' ') . The join method returns a string with all array elements joined by the provided separator. Copied!

How do you add a comma to an array?

Join Together an Array as a String with Commas. When you need to join together every item in a JavaScript array to form a comma-separated list of values, use . join(",") or equivalently just . join() without any arguments at all.

How do you convert an array to a string separated by commas?

join method. To convert an array to a comma-separated string, call the join() method on the array, passing it a string containing a comma as a parameter. The join method returns a string containing all array elements joined by the provided separator.

How do you add comma-separated values in an array?

Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.


1 Answers

One option would be to pop the last item, then join all the rest by commas, and concatenate with and plus the last item:

const input = ['one', 'two', 'three', 'four'];  const last = input.pop();  const result = input.join(', ') + ' and ' + last;  console.log(result);

If you can't mutate the input array, use slice instead, and if there might only be one item in the input array, check the length of the array first:

function makeString(arr) {    if (arr.length === 1) return arr[0];    const firsts = arr.slice(0, arr.length - 1);    const last = arr[arr.length - 1];    return firsts.join(', ') + ' and ' + last;  }    console.log(makeString(['one', 'two', 'three', 'four']));  console.log(makeString(['one']));
like image 194
CertainPerformance Avatar answered Sep 23 '22 09:09

CertainPerformance