What I want is something like Array.join(separator)
, but which takes a second argument Array.join(separator, beforeLastElement)
, so when I say [f
Though its a late answer, adding some approaches.
Method 1: Using Array.splice() add the last delimiter
before last element and join and remove the last two ,
.
function join(arr,last)
{
if(!Array.isArray(arr)) throw "Passed value is not of array type.";
last = last || ' and '; //set 'and' as default
(arr.length>1 && arr.splice(-1,0,last));
arr = arr.join().split("");
arr[arr.lastIndexOf(",")]="";
arr[arr.lastIndexOf(",")]="";
return arr.join("");
}
console.log( join([1]) ); //single valued array
console.log( join([1,2]) ); //double valued array
console.log( join([1,2,3]) ); //more than 2 values array,
console.log( join([1,2,3],' or ') ); //with custom last delimiter
console.log( join("name") ); //Non-array type
Method 2: Using Array.reduce() to construct the string by traversing each element.
function join(arr,last)
{
if(!Array.isArray(arr)) throw "Passed value is not of array type.";
last=last||' and ';
return arr.reduce(function(acc,value,index){
if(arr.length<2) return arr.join();
return acc + (index>=arr.length-2 ? index>arr.length-2 ? value : value+last : value+",");
},"");
}
console.log( join([1]) ); //single valued array
console.log( join([1,2]) ); //double valued array
console.log( join([1,2,3]) ); //more than 2 values array,
console.log( join([1,2,3,4],' or ') ); //with custom last delimiter
console.log( join("name") ); //Non-array type