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?
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]]
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 (ie 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>
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.