Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group by two array by index in javascript with es6 or lodash?

We have same two arrays to groupby theme by index. Two arrays with same length and different value like blow. How to groupby two array with their index by ES6 reduce or lodash?

array1 = [1,2,3,4] OR [{a:1},{b:2},{c:3},{d:4}]
array2 = [5,6,7,8] OR [{e:5},{f:6},{g:7},{h:8}]

finalArray = [[1,5],[2,6],[3,7],[4,8]]

I'm trying with different ways like group by with reduce in es6 or lodash concat but i can't find best solution for my problems.

like image 666
Pooya Golchian Avatar asked Nov 06 '25 05:11

Pooya Golchian


1 Answers

Try this:

let array1 = [1, 2, 3, 4];
let array2 = [5, 6, 7, 8];
let res = array1.map((value, index) => {
  return [value, array2[index]]
})
console.log(res);

If it is array of objects

let array1 = [{a:1},{b:2},{c:3},{d:4}];
let array2 = [{e:5},{f:6},{g:7},{h:8}];

let res = array1.map((value, index) => {
  return [Object.values(value)[0],Object.values(array2[index])[0]]
})
console.log(res)
like image 121
Saurabh Agrawal Avatar answered Nov 07 '25 21:11

Saurabh Agrawal