Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use lodash javascript to full join two-dimensional array

I have two two-dimensional array.

var arr1=[[1,20],[2,30]];
var arr2=[[2,40],[3,50]];

This is expected output:

[[1,20,null],[2,30,40],[3,null,50]]

It is like full join of two data frames. The logic is similar to this pseudo code:

df1.join(df2, df1[col_1] == df2[col_1], 'full')

but this case is for two-dimensional array. Can lodash do this? If not, how to do it in vanilla javascript?

like image 294
field210 Avatar asked May 04 '26 16:05

field210


2 Answers

Well, lodash can't do this, but we can:

function flatten2d(arr1, arr2) {
  const o1 = _.fromPairs(arr1);
  const o2 = _.fromPairs(arr2);
  const result = [];

  _.forEach(o1, (v, k) => {
    const v2 = o2[k] || null;
    result.push([k|0, v, v2]);
    delete o2[k];
  });

  // at this point, only items non-existing
  // in o1 are left in o2
  _.forEach(o2, (v, k) => {
    result.push([k|0, null, v]);
  });

  return result;
}

Testing:

flatten2d([[1,20],[2,30]], [[2,40],[3,50]])

Result:

[[1,20,null], [2,30,40], [3,null,50]]
like image 100
Styx Avatar answered May 07 '26 06:05

Styx


If you don't have duplicate id's in any single array then you can try combine them, and group them using groupBy with first element (i.e. the key 0), and if you have duplicates, anyway I am not sure what exactly output you are looking for! Here is what you can do:

    _(arr1.concat(arr2)).groupBy('0').map(v=>
        [v[0][0]].concat(v.length > 1 ? v.map(m=>m[1]) : [v[0][1], null])
    ).value();

Here is an working snippet for you:

var arr1=[[1,20],[2,30]];
var arr2=[[2,40],[3,50]];

var res = _(arr1.concat(arr2)).groupBy('0').map(v=>
        [v[0][0]].concat(v.length > 1 ? v.map(m=>m[1]) : [v[0][1],null])
    ).value();
    
 console.log(JSON.stringify(res));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
like image 36
Koushik Chatterjee Avatar answered May 07 '26 06:05

Koushik Chatterjee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!