简体   繁体   中英

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

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):

  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 :

 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] .

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM