2015-11-16 69 views
2

我有一個複雜的任務,將一個數據數組切片並切成一個合理的JSON對象。第一步是根據元素的內容將數組分割成更小的數組。根據內容切片陣列

在這個簡化版本中,我想將一個大陣列分成一系列由「that」定義的小陣列。

鑑於此陣:

that, thing, thing, that, thing, that, thing, thing, thing 

我要回:

[that, thing, thing], 
[that, thing], 
[that, thing, thing, thing], 
+2

可否請你發佈你已經嘗試這樣的代碼,我們可以指導你更好? –

+0

因此,爲了澄清,你想要將一個數組分割成一個以鍵值'that'開頭的數組數組? –

+1

我沒有看到什麼可能是一個*「明智的JSON對象」*在你的問題的上下文中...... –

回答

1

這是很容易與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); 
}, [])); 

JSFiddle

+0

真棒新的數組函數與.reduce()學習,創造奇蹟! – icicleking

1
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) 
0

這將是體力勞動。我推薦組合indexOf(查找「那個」)和splice(刪除相關的子數組)。

var input = ["that", "thing", "thing", "that", "thing", "that", "thing", "thing", "thing"]; 
var output = []; 
for (var idx = input.indexOf("that", 1); idx !== -1; idx = input.indexOf("that", 1)) { 
    output.push(input.splice(0, idx)); 
} 
output.push(input); 
0

快速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>

0

您可以使用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 ] ]