简体   繁体   中英

merging 2 multidimensional arrays at the same index

javascript

I'm trying to either merge 2 multidimensional arrays at the same index or randomize the same index of both arrays the same.

var arr1 = [[a, b, c], [d, e], [f, g, h, i]]
var arr2 = [[1, 2, 3], [5, 6], [7, 8, 9, 10]]

preferredResult = [{a: 1, b: 2, c: 3}, {d: 5, e:6}, {f: 7, g: 8, h: 9, i: 10}]

I've tried .maps, nested for loops, .push in different variations and have not been able to figure this out.

Alternatively, if I could figure out how randomize two arrays of arrays in the same way, that would work as well, ie: the letters in arr1[0] and numbers in arr2[0] could be set to the same randomization, then arr1[1] & arr2[1] and so on.

function merge(arr1, arr2) {
   return arr1.map(function (arr, i) {
      return mergeIntoObject(arr1[i], arr2[i])); 
   };
}

function mergeIntoObject(arr1, arr2) {
  var result = {};
  arr1.forEach((arr, i) => {
    result[arr1[i]] = arr2[i];
  });
  return result;
}

merge(arr1, arr2);

Using embedded for loops

 var arr1 = [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i']] var arr2 = [[1, 2, 3], [5, 6], [7, 8, 9, 10]] var result = [] for (let i = 0; i < arr1.length; i++){ let obj = {}; for (let j = 0; j < arr1[i].length; j++){ obj[arr1[i][j]]=arr2[i][j] } result.push(obj); } console.log(result) 

You can use array#map and array#reduce

 const arr1 = [['a', 'b', 'c'], ['d','e' ], ['f', 'g', 'h', 'i']], arr2 = [[1, 2, 3], [5, 6], [7, 8, 9, 10]], result = arr1.map(function(a, i){ return a.reduce(function(r, v, j){ r[v] = arr2[i][j]; return r; }, {}); }); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

Lodash can be super helpful.

 var arr1 = [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i']] var arr2 = [[1, 2, 3], [5, 6], [7, 8, 9, 10]] var out = _.zipWith(arr1, arr2, (x,y)=>_.fromPairs(_.zip(x,y))); console.log(out) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> 

zip will combine 2 arrays into pairs and zipWith will do the same but let you choose how to combine them.

Use map & forEach method

 var arr1 = [ ['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i'] ], arr2 = [ [1, 2, 3], [5, 6], [7, 8, 9, 10] ], m = arr1.map(function(item, index) { let tempObj = {}; item.forEach(function(item2, index2) { tempObj[item2] = arr2[index][index2]; }); return tempObj; }); console.log(m) 

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