[英]How to get keys and values of arrays inside Multidimensional array in javascript
I Have a multidimensional array such as 我有一个多维数组,例如
MultArrary = [
['a','b'],
['c','d'],
['f','g']
]
What i need is to get the key and value of each array inside the array and push it into another array 我需要的是获取数组内部每个数组的键和值,并将其推入另一个数组
Expected array1 = ['a','c','f'];
expected array2 = ['b','d','g'];
Any ideas how to achieve this with javascript or rxjs will be great 关于如何使用javascript或rxjs实现此目标的任何想法都很棒
Easiest thing to do (while not syntatically correct, see the comments below your question) in your case is to use a Map (provided you are within an ecmascript6 capable environment): 在您的情况下,最简单的操作(虽然在语法上不正确,请参阅问题下方的注释)是使用Map (前提是您位于具备ecmascript6功能的环境中):
var MultiArray = [ ['a', 'b'], ['c', 'd'], ['f', 'g'] ]; var m = new Map(MultiArray); var index0 = Array.from(m.keys()); var index1 = Array.from(m.values()); console.log(index0, index1);
Using Underscore.js you can do it with unzip : 使用Underscore.js,您可以使用unzip做到这一点:
var MultArrary = [ ['a', 'b'], ['c', 'd'], ['f', 'g'] ]; var rst = _.unzip(MultArrary); //[['a','c','f'],['b','d','g']] console.log(rst);
<script data-require="underscore.js@1.8.3" data-semver="1.8.3" src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
You could use a single approach and build the result in one task. 您可以使用一种方法,并将结果构建在一个任务中。
Your wanted result is in pivot[0]
and pivot[1]
. 您想要的结果是在
pivot[0]
和pivot[1]
。
var multArrary = [['a', 'b'], ['c', 'd'], ['f', 'g']], pivot = multArrary.reduce(function (r, a) { a.forEach(function (b, i) { r[i] = r[i] || []; r[i].push(b); }); return r; }, []); console.log(pivot);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.