2013-02-25 25 views
12

Quello che voglio è qualcosa come Array.join(separator), ma che prende un secondo argomento Array.join(separator, beforeLastElement), quindi quando dico [foo, bar, baz].join(", ", " or") mi piacerebbe ottenere "foo, bar or baz". Immagino di poter scrivere una funzione che utilizza Array.slice per separare l'ultimo elemento, ma c'è un metodo ben noto che potrei usare invece?C'è un modo per unire gli elementi in un array js, ma lasciare che l'ultimo separatore sia diverso?

risposta

6

No, questo è abbastanza specifico da dover scrivere una funzione personalizzata. La buona notizia è, come hai detto, quando usi Array.join per occuparti di tutti i separatori, l'ultimo sarà abbastanza facile da aggiornare.

23

Sei sicuro che una funzione dovrebbe essere predefinita solo per quello?

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

Si noti che questo assume 'a.length> 1'. Dovresti considerare 'a.length <= 1' pure –

+0

Non sono sicuro che dovrebbe, mi chiedevo solo se ci fosse, e se non fosse stato concordato un metodo per farlo. Sarebbe sciocco scrivere qualcosa di diverso da tutti gli altri. –

11

Costruzione off di risposta di @ dystroy:

function formatArray(arr){ 
    var outStr = ""; 
    if (arr.length === 1) { 
     outStr = arr[0]; 
    } else if (arr.length === 2) { 
     //joins all with "and" but no commas 
     //example: "bob and sam" 
     outStr = arr.join(' and '); 
    } else if (arr.length > 2) { 
     //joins all with commas, but last one gets ", and" (oxford comma!) 
     //example: "bob, joe, and sam" 
     outStr = arr.slice(0, -1).join(', ') + ', and ' + arr.slice(-1); 
    } 
    return outStr; 
} 

usi Esempio:

formatArray([]);    //"" 
formatArray(["a"]);    //"a" 
formatArray(["a","b"]);   //"a and b" 
formatArray(["a","b","c"]);  //"a, b, and c" 
formatArray(["a","b","c","d"]); //"a, b, c, and d" 
+0

Ottimo! Comunque piccolo bug sulla riga 'outStr = arr.slice (0, -1) .join (',') + ', e' + arr.slice (-1);' Metti uno spazio dopo la virgola in 'join () ' –

+1

@AndyB oops, sì hai ragione. Ho aggiunto lo spazio ora. Grazie! –

+0

Funziona come un fascino. :) –

4
Array.prototype.join2 = function(all, last) { 
    var arr = this.slice();     //make a copy so we don't mess with the original 
    var lastItem = arr.splice(-1);   //strip out the last element 
    arr = arr.length ? [arr.join(all)] : []; //make an array with the non-last elements joined with our 'all' string, or make an empty array 
    arr.push(lastItem);      //add last item back so we should have ["some string with first stuff split by 'all'", last item]; or we'll just have [lastItem] if there was only one item, or we'll have [] if there was nothing in the original array 
    return arr.join(last);     //now we join the array with 'last' 
} 

> [1,2,3,4].join2(', ', ' and '); 
>> "1, 2, 3 and 4" 
0

Per nodejswebpack e altri Fardellatrici utenti: c'è un pacchetto join-array

const join = require('join-array'); 
const names = ['Rachel','Taylor','Julia','Robert','Jasmine','Lily','Madison']; 
const config = { 
    array: names, 
    separator: ', ', 
    last: ' and ', 
    max: 4, 
    maxMessage:(missed)=>`(${missed} more...)` 
}; 
const list = join(config); //Rachel, Taylor, Julia, (3 more...) and Madison 
Problemi correlati