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の経験がありません。ただし、下位互換性が必要な場合は、ポリフィルのように見えます。Array#reduce

于 2012-08-03T17:59:35.307 に答える
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など)をサポートする必要がある場合は、最初にこのポリフィルを追加します。

//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 に答える
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 に答える