0

我想通过一个/或多个给定的分隔符将一个数组拆分为一个子数组列表。

像这样的东西:

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

splitArray(myArray, mySeperators)

应该导致:

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

源数组可以多次包含分隔符。如何做到这一点?

当它使解决方案更容易时,我使用 mootools 作为基础库。

4

4 回答 4

4

鉴于 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 的经验;但是,如果需要向后兼容,它似乎是 polyfill 。Array#reduce

于 2012-08-03T17:59:35.307 回答
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);

​</p>

于 2012-08-03T18:16:16.110 回答
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) );
于 2012-08-03T18:13:15.737 回答
1

这应该在浏览器中非常通用,并且不需要任何库:

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;
}

如果你需要支持没有内置 indexOf 支持的浏览器(例如 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;
  };
}
于 2012-08-03T18:14:08.563 回答