2012-08-03 73 views
0

我想將一個數組分割成一個或多個給定分隔符的子數組列表。javascript:由一個給定的分隔符將數組分割成子陣列

是這樣的:

var myArray = [null, 5, 'whazzup?', object, '15', 34.6]; 
var mySeperators = [null, '15']; 

splitArray(myArray, mySeperators) 

應導致在於:

[[], [5, 'whazzup?', object], [34.6]] 

源陣列可以包含分隔符多次。如何做到這一點?

當它使解決方案更容易,我使用mootools作爲基礎庫。

+0

這是分隔符! – biziclop 2012-08-03 17:56:45

+0

該解決方案是否可以使用jQuery? – 2012-08-03 17:59:38

+0

可以有多個空值/ 15嗎? – epascarello 2012-08-03 18:00:45

回答

3

考慮的ECMAScript 5,有可能與使用的Array#reduce做到這一點:

myArray.reduce(function(currentArrays, nextItem) { 
    if(~mySeparators.indexOf(nextItem)) 
     currentArrays.push([]); 
    else 
     currentArrays[currentArrays.length - 1].push(nextItem); 

    return currentArrays; 
}, [[]]); 

我有MooTools的沒有經驗;但是,如果需要向後兼容性,則它爲appears to polyfill Array#reduce

+0

非常令人印象深刻:) – kraiz 2012-08-03 19:25:10

1

回答假設Array.indexOf支持

function splitArray(orgArr, splits){ 
    var i, newArr=[], vals = orgArr.slice(); //clone the array so we do not change the orginal 
    for (i=vals.length-1;i>=0;i--) { //loop through in reverse order 
     if (splits.indexOf(vals[i]) !== -1) { //if we have a match time to do a split 
     newArr.unshift(vals.splice(i+1, vals.length-i)); //grab the indexes to the end and append it to the array 
     vals.pop(); //remove the split point 
     } 
    } 
    newArr.unshift(vals); //add any of the remaining items to the array 
    return newArr; //return the split up array of arrays 
} 

var myArray = [null, 5, 'whazzup?', {}, '15', 34.6]; 
var mySeperators = [null, '15']; 
console.log(splitArray(myArray, mySeperators)); 
1

這應該是跨瀏覽器相當普遍,並且不需要任何庫:如果您需要支持的瀏覽器沒有內置的indexOf支持

function splitArray(a, seps) { 
    var i, res = [], parts = []; 
    for (i = 0; i < a.length; i++) { 
    if (seps.indexOf(a[i]) > -1) { 
     res.push(parts); 
     parts = []; 
    } else { 
     parts.push(a[i]); 
    } 
    } 
    res.push(parts); 
    return res; 
} 

(如IE 6-8)然後首先添加這個polyfill:

//This prototype is provided by the Mozilla foundation and 
//is distributed under the MIT license. 
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license 

if (!Array.prototype.indexOf) 
{ 
    Array.prototype.indexOf = function(elt /*, from*/) 
    { 
    var len = this.length; 

    var from = Number(arguments[1]) || 0; 
    from = (from < 0) 
     ? Math.ceil(from) 
     : Math.floor(from); 
    if (from < 0) 
     from += len; 

    for (; from < len; from++) 
    { 
     if (from in this && 
      this[from] === elt) 
     return from; 
    } 
    return -1; 
    }; 
} 
+0

JavaScript僅支持對象中的字符串鍵,因此這可能無法按預期工作。此外,這將打破所有數組元素'x',其中'{}'中的x.toString()。 – 2012-08-03 18:15:02

+0

考慮測試用例'splitArray(['null','toString'],['null'])''。它目前產生'[[],[],[]]''。 – 2012-08-03 18:17:45

+0

@Charmander,索引很好,我更新了使用indexOf和polyfill選項。 – kanaka 2012-08-03 18:21:12

1

試試這個:)

http://jsfiddle.net/baP66/1/

var myArray = [null, 5, 'whazzup?', {}, '15', 34.6]; 
var mySeperators = [null, '15']; 

var splitArray = function(arr, aSep){ 
    var acc = [[]]; 
    var sp = function(){ 
     for (var i=0; i<arr.length; i++){ 
      var item = arr[i]; 
      var last = acc[acc.length-1]; 

      if (aSep.indexOf(item) > -1){ 
       acc.push([]); 
      }else{ 
       last.push(item); 
      } 
     }; 
    }; 
    sp(); 

    return acc; 
}; 

var res = splitArray(myArray, mySeperators); 

console.log(res);