Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn array into comma separated grammatically correct sentence

If I have an array in Javascript that looks like

searchComponents = ['element1', 'element2', 'element3'];

What is the necessary logic to turn it into a sentence like:

"element1, element2, and element3"

Likewise, if there are only two elements it should read like:

"element1 and element2"

and so on and so forth. I am stuck.

like image 430
Alex Neigher Avatar asked May 05 '14 23:05

Alex Neigher


People also ask

How do you get a comma-separated value from an array?

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 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.


3 Answers

One easy solution:

function arrayToSentence (arr) {
    var last = arr.pop();
    return arr.join(', ') + ' and ' + last;
}

console.log(arrayToSentence(['one','two','three']));

JS Fiddle demo.

And a slightly more complex/ridiculous solution (because who doesn't like silly, occasionally...):

function arrayToSentence (arr) {
    var len = arr.length;
    return arr.reduce(function(a,b,c){
        return a + (c - 1 === length ? ', ' : ' and ') + b;
    });
}

console.log(arrayToSentence(['one','two','three']));

JS Fiddle demo.

References:

  • Array.prototype.join().
  • Array.prototype.pop().
  • Array.prototype.reduce().
like image 100
David Thomas Avatar answered Oct 12 '22 13:10

David Thomas


function toSentence(arr) {
  return arr.slice(0, -2).join(', ') + 
    (arr.slice(0, -2).length ? ', ' : '') + 
    arr.slice(-2).join(' and ');
}

usage

toSentence([1])

1

toSentence([1, 2])

1 and 2

toSentence([1, 2, 3])

1, 2 and 3

toSentence([1, 2, 3, 4, 5, 6])

1, 2, 3, 4, 5 and 6

like image 37
theliberalsurfer Avatar answered Oct 12 '22 13:10

theliberalsurfer


Here's a one liner:

const arrayToSentence = (a) => [a.slice(0, -1).join(', '), a.pop()].filter(w => w !== '').join(' and ');

console.log(arrayToSentence(['foo', 'bar', 'baz']));
console.log(arrayToSentence(['foo', 'bar']));
console.log(arrayToSentence(['foo']));
console.log(arrayToSentence([]));
like image 5
Rimian Avatar answered Oct 12 '22 14:10

Rimian