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

前端 未结 11 780
灰色年华
灰色年华 2021-02-03 17:40

What I want is something like Array.join(separator), but which takes a second argument Array.join(separator, beforeLastElement), so when I say [f

11条回答
  •  无人及你
    2021-02-03 18:00

    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

提交回复
热议问题