[英]Re-arrange array
我需要以特定方式重新排列數組。
我的輸入數組結構是這樣的(已編輯):
[
[[elem1-1,elem1-2,elem1-3],int1],
[[elem2-1,elem2-2,elem2-3],int2]
]
解釋:“elem[nn]”表示一個元素,“int[n]”是一個整數。
使用上面的結構使我在 2 個級別中編寫一個非常復雜的循環來獲取我的數據,我需要重新排列相同的數組以使其看起來像這樣並避免第二個循環:
[
[elem1-1,int1],
[elem1-2,int1],
[elem1-3,int1],
[elem2-1,int2],
...
]
數組之間的主要區別在於,第二個數組包含行中的所有元素,並為輸入的行內元素重復 int 值。
關鍵是我想在不使用任何 foreach 指令的情況下重新排列這個數組(這將導致相同的 2 級循環),只需使用 map、reduce 等等。
我嘗試了數組映射,但仍然無法正常工作。 見下面的代碼:
//arr_in is the first array structure and arr_out is my expected output
var arr_out = arr_in.map( function (elem){
if (elem[0].size()>1) {
return [//here is the problem, i guess]
}
else {
return [elem[0], elem[1]]
}
});
提前致謝
根據提供的代碼,我猜測arr_in
是一個包含以下形式數組的二維數組: [elem1-1, elem1-2, ..., int1]
。 如果是這樣,則數組及其子項上的forEach
將執行以下操作:
var arr_out = [];
arr_in.forEach( function (sub) {
// sub = sub.slice(0); // uncomment this line if you don't want to alter the original array arr_in
var int = sub.pop(); // get the last item of this sub array, which is the "int"
sub.forEach(function(elem) { // for each other element left in the sub array
arr_out.push([elem, int]); // push a pair to the result array consisting of the current element and the "int"
});
});
使用箭頭函數哪個更短:
let arr_out = [];
arr_in.forEach( sub => {
let int = sub.pop();
sub.forEach(elem => arr_out.push([elem, int]));
});
如果您想要更實用的方式,您可以隨時使用reduce
:
let arr_out = arr_in.reduce((acc, sub) => {
let int = sub.pop();
sub.forEach(elem => acc.push([elem, int]));
return acc;
}, []);
演示:
var arr_in = [ ["elem1", "elem2", "elem3", 7], ["elem1", 5], ["elem1", "elem2", 9] ]; let arr_out = []; arr_in.forEach( sub => { let int = sub.pop(); sub.forEach(elem => arr_out.push([elem, int])); }); console.log(arr_out);
如果索引為奇數,您可以通過映射內部數組或僅返回最后一個結果來減少數組。
var array = [[['elem1-1','elem1-2','elem1-3'], 'int1'], [['elem2-1','elem2-2','elem2-3'], 'int2']], result = array.reduce( (r, [a, b]) => r.concat(a.map(v => [v, b])), [] ); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.