What I want is something like Array.join(separator)
, but which takes a second argument Array.join(separator, beforeLastElement)
, so when I say [f
compact version :)
function customJoin(arr,s1,s2){
return(arr.slice(0,-1).join(s1).concat(arr.length > 1 ? s2 : '', arr.slice(-1)));
}
/*
arr: data array
s1: regular seperator (string)
s2: last seperator (string)
*/
function customJoin(arr,s1,s2){
return(arr.slice(0,-1).join(s1).concat(arr.length > 1 ? s2 : '', arr.slice(-1)));
}
let arr1 = ['a','b','c','d'];
let arr2 = ['singleToken'];
console.log(customJoin(arr1,',',' and '));
//expected: 'a,b,c and d'
console.log(customJoin(arr1,'::',' and finally::'));
//expected: 'a::b::c and finally::d'
console.log(customJoin(arr2,',','and '));
//expected: 'singleToken'