Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to join the elements in an js array, but let the last separator be different?

Tags:

javascript

What I want is something like Array.join(separator), but which takes a second argument Array.join(separator, beforeLastElement), so when I say [foo, bar, baz].join(", ", " or") I would get "foo, bar or baz". I guess I could write a function that used Array.slice to separate out the last element, but is there some well known method that I could use instead?

like image 501
Eivind Eidheim Elseth Avatar asked Feb 25 '13 14:02

Eivind Eidheim Elseth


People also ask

How do I get an array without the last element?

Use the Array. slice() method to remove the last element from an array, e.g. const withoutLast = arr. slice(0, -1); . The slice method will return a copy of the original array excluding the last element.

How do you join elements in an array?

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 would you access the 2nd to last element in an array?

To get the second to last element in an array, call the at() method on the array, passing it -2 as a parameter, e.g. arr.at(-2) . The at method returns the array element at the specified index. When passed a negative index, the at() method counts back from the last item in the array.

Which method of the array removes and returns the last element join ()?

The pop() method removes the last element from an array and returns that element.


2 Answers

May I suggest:

['tom', 'dick', 'harry'].join(', ').replace(/, ([^,]*)$/, ' and $1') > "tom, dick and harry" 
like image 34
Joseph Avatar answered Sep 28 '22 08:09

Joseph


There's no predefined function, because it's quite simple.

var a = ['a', 'b', 'c']; var str = a.slice(0, -1).join(',')+' or '+a.slice(-1); 

There's also a specification problem for the main use case of such a function which is natural language formatting. For example if we were to use the Oxford comma logic we would have a different result than what you're looking for:

// make a list in the Oxford comma style (eg "a, b, c, and d") // Examples with conjunction "and": // ["a"] -> "a" // ["a", "b"] -> "a and b" // ["a", "b", "c"] -> "a, b, and c" exports.oxford = function(arr, conjunction, ifempty){     let l = arr.length;     if (!l) return ifempty;     if (l<2) return arr[0];     if (l<3) return arr.join(` ${conjunction} `);     arr = arr.slice();     arr[l-1] = `${conjunction} ${arr[l-1]}`;     return arr.join(", "); } 

So it seems better to let this problem in userland.

like image 198
Denys Séguret Avatar answered Sep 28 '22 09:09

Denys Séguret