[英]Trying to split array into specified amount of subarrays in javascript
[英]javascript: split an array into subarrays by a given seperator
我想通過一個或多個給定的分隔符將數組拆分為子數組列表。
像這樣的東西:
var myArray = [null, 5, 'whazzup?', object, '15', 34.6];
var mySeperators = [null, '15'];
splitArray(myArray, mySeperators)
應該導致:
[[], [5, 'whazzup?', object], [34.6]]
源數組可以多次包含分隔符。 如何做到這一點?
當它使解決方案變得更容易時,我正在使用mootools作為基礎庫。
給定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
。
答案假設支持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) );
這在瀏覽器中應該很普遍,不需要任何庫:
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;
};
}
嘗試這個 :)
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.