# javascriptでオブジェクトを含む多次元配列を平坦化する方法

``````myarr[0] =[{"name":"john","age":"50","location":"san diego"}
,{"name":"jane","age":"25","location":"new york"}
,{"name":"susane","age":"10","location":"los angeles"}
];
myarr[1] =[{"smoker":"yes","drinker":"no","insured":"no"}
,{"smoker":"no","drinker":"no","insured":"yes"}
,{"smoker":"no","drinker":"yes","insured":"no"}
];
myarr[1] =[{"status":"married","children":"none"}
,{"status":"unmarried","children":"one"}
,{"status":"unmarried","children":"two"}
];
``````
1
` concat ` こちらをご覧ください。

flattenは多次元配列を平坦化することを意味します - それを一次元配列にする - 混乱のために残念です。たとえば、すべてのオブジェクトを昇順で含む配列です。

## 1 答え

``````function merge(a, b) {
a = a || { };
for(var k in b)
if(b.hasOwnProperty(k))
a[k] = b[k];
return a;
}
``````

``````var flat = [ ];
for(var i = 0; i < myarr.length; ++i)
for(var j = 0; j < myarr[i].length; ++j)
flat[j] = merge(flat[j], myarr[i][j]);
``````

そしてそれを並べ替える：

``````flat.sort(function(a, b) {
a = a.location;
b = b.location;
if(a < b)
return -1;
if(a > b)
return 1;
return 0;
});
``````

Demo (run with your JavaScript console open): http://jsfiddle.net/ambiguous/twpUF/

2

その素晴らしい応答に感謝します

JavaScript - 日本のコミュニティ
2 参加者の