Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to .join() arrays nicely

Tags:

I find Array.prototype.join() method very useful when constructing strings from arrays, like

"one two three".split(' ').join(', '); 

But very often I want to generate a string like this:

"one, two and three" 

The method I use is this:

var parts = "one two three".split(' '); parts.slice(0, parts.length-1).join(', ') + ' and ' + parts.slice(-1) 

This generates what I want, however is an ugly solution I should put into a separate function.

I love one liners and believe there should be more elegant one-liner in JS to accomplish this task. Can someone provide me with one ?

EDIT

Please no need to comment that it is a bad practice to write unreadable code. I ask for one! :) I have learned a lot from one liners about the language constructs and so have a situation where I see a possibility for one. No offense.

FINAL EDIT I appreciate Pavlo answer as it really shows how easily one liner can become a beautiful readable code. Since I was asking for a one liner so as per my question h2ooooooo gets the highest score.

like image 511
lukas.pukenis Avatar asked Oct 02 '13 11:10

lukas.pukenis


People also ask

How do you join objects in arrays?

join() The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

How do you merge two arrays using the spread Operator?

You can use either the spread operator [... array1, ... array2] , or a functional way []. concat(array1, array2) to merge 2 or more arrays.

How do I combine two arrays?

The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.

How do you join arrays in Java?

To join elements of given string array strArray with a delimiter string delimiter , use String. join() method. Call String. join() method and pass the delimiter string delimiter followed by the string array strArray .


1 Answers

I'm surprised with the amount of cryptic solutions and the fact that nobody used pop():

function splitJoin(source) {     var array = source.split(' ');     var lastItem = array.pop();      if (array.length === 0) return lastItem;      return array.join(', ') + ' and ' + lastItem; }  splitJoin('one two three'); // 'one, two and three' splitJoin('one two');       // 'one and two' splitJoin('one');           // 'one' 

Edit: Modified to properly work for any string.

like image 108
Pavlo Avatar answered Nov 20 '22 01:11

Pavlo