jQuery Data Type How to - Turn array into comma separated grammatically correct sentence








Question

We would like to know how to turn array into comma separated grammatically correct sentence.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--   w ww .jav  a  2 s. c  o  m-->
function arrayToSentence (arr) {
    var last = arr.pop();
    return arr.join(', ') + ' and ' + last;
}
document.writeln(arrayToSentence(['one','two','three']));

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: