我想通过一个/或多个给定的分隔符将一个数组拆分成一个子数组列表。
类似的东西:
var myArray = [null, 5, 'whazzup?', object, '15', 34.6];
var mySeperators = [null, '15'];
splitArray(myArray, mySeperators)
应该导致:
[[], [5, 'whazzup?', object], [34.6]]
源数组可以多次包含分隔符。怎么做到这一点?
当它使解决方案更容易时,我使用mootools作为基础库。
答案 0 :(得分: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没有经验;但是,appears to polyfill Array#reduce
,如果需要向后兼容性。
答案 1 :(得分: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) );
答案 2 :(得分: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;
};
}
答案 3 :(得分: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);