我有一個複雜的任務,將一個數據數組切片並切成一個合理的JSON對象。第一步是根據元素的內容將數組分割成更小的數組。根據內容切片陣列
在這個簡化版本中,我想將一個大陣列分成一系列由「that」定義的小陣列。
鑑於此陣:
that, thing, thing, that, thing, that, thing, thing, thing
我要回:
[that, thing, thing],
[that, thing],
[that, thing, thing, thing],
我有一個複雜的任務,將一個數據數組切片並切成一個合理的JSON對象。第一步是根據元素的內容將數組分割成更小的數組。根據內容切片陣列
在這個簡化版本中,我想將一個大陣列分成一系列由「that」定義的小陣列。
鑑於此陣:
that, thing, thing, that, thing, that, thing, thing, thing
我要回:
[that, thing, thing],
[that, thing],
[that, thing, thing, thing],
這是很容易與Array.reduce()
做到:
var array = ["that", "thing", "thing", "that", "thing", "that", "thing", "thing", "thing"];
console.log(array.reduce(function(prev, cur, idx, arr) {
if (cur === "that") {
// start a new sub-array
prev.push(["that"]);
}
else {
// append this token onto the current sub-array
prev[prev.length - 1].push(cur);
}
return (prev);
}, []));
真棒新的數組函數與.reduce()學習,創造奇蹟! – icicleking
var arr = ['that', 'thing', 'thing', 'that', 'thing', 'that', 'thing', 'thing', 'thing'];
var subArrays = [];
var subArrayItem = [];
arr.forEach(function(arrItem) {
if(arrItem == 'that') {
if(subArrayItem.length) // avoid pushing empty arrays
subArrays.push(subArrayItem)
subArrayItem = []
}
subArrayItem.push(arrItem)
})
if(subArrayItem.length) // dont forget the last array
subArrays.push(subArrayItem)
快速reduce
應該修復它:
var src = ["that", "thing", "thing", "that", "thing", "that", "thing", "thing", "thing"]
var dest = src.reduce(function(p,d) {
if (d === "that") {
p.push([d]);
} else {
p[p.length-1].push(d);
}
return p;
},[]);
$("#json").text(JSON.stringify(dest));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="json"></div>
您可以使用lastIndexOf,slice和unshift。
function test (a, b, item) {
var i = a.lastIndexOf(item);
while (i != -1) {
b.unshift(a.slice(i));
a = a.slice(0, i);
i = a.lastIndexOf(item);
}
return b;
}
var arr1 = [1, 2, 3, 1, 2, 1, 2, 3, 4];
var arr2 = [];
test(arr1, arr2, 1);
console.log(arr2);
使用到的NodeJS運行的結果是:
[ [ 1, 2, 3 ], [ 1, 2 ], [ 1, 2, 3, 4 ] ]
可否請你發佈你已經嘗試這樣的代碼,我們可以指導你更好? –
因此,爲了澄清,你想要將一個數組分割成一個以鍵值'that'開頭的數組數組? –
我沒有看到什麼可能是一個*「明智的JSON對象」*在你的問題的上下文中...... –