本文介绍了JavaScript中的两个数组内部联接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是我拥有的2个数组,
Following are the 2 arrays I have,
var g= [
{ id: 36, name: 'AAA', goal: 'yes' },
{ id: 40, name: 'BBB', goal: 'yes' },
{ id: 39, name: 'JJJ', goal: 'yes' },
{ id: 27, name: 'CCC', goal: 'yes' }];
var c= [
{ id: 36, color:"purple" },
{ id: 40, color:"purple" },
{ id: 100, color:"pink"} ];
所需的输出("id"上的左连接):
Desired output(left join on 'id'):
res = [{ id: 36, name: 'AAA', goal: 'yes' , color:"purple"}, { id: 40, name: 'BBB', goal: 'yes', color:"purple" }]
这是进行合并的现有逻辑,但我正在寻找左连接的逻辑:
here's an existing logic which does merger but I'm looking for a logic for left join:
function mergeBy(key, data) {
return Array.from(data
.reduce((m, o) => m.set(o[key], { ...m.get(o[key]), ...o }), new Map)
.values()
);
}
推荐答案
为您准备了一些加入,请选择!
Here are some joins for you, take your pick!
function* innerJoin(a, b, key) {
let idx = new Map(b.map(x => [key(x), x]));
for (let x of a) {
let k = key(x);
if (idx.has(k))
yield {...x, ...idx.get(k)};
}
}
function* leftJoin(a, b, key) {
let idx = new Map(b.map(x => [key(x), x]));
for (let x of a) {
let k = key(x);
yield idx.has(k) ? {...x, ...idx.get(k)} : x;
}
}
function* rightJoin(a, b, key) {
let idx = new Map(a.map(x => [key(x), x]));
for (let x of b) {
let k = key(x);
yield idx.has(k) ? {...idx.get(k), ...x} : x;
}
}
//
var A = [
{id: 1, a: 'a1'},
{id: 2, a: 'a2'},
{id: 7, a: 'a3'},
{id: 8, a: 'a4'}
];
var B = [
{id: 1, b: 'b1'},
{id: 2, b: 'b2'},
{id: 9, b: 'b3'}
];
console.log('INNER:')
console.log(...innerJoin(A, B, x => x.id))
console.log('LEFT')
console.log(...leftJoin(A, B, x => x.id))
console.log('RIGHT')
console.log(...rightJoin(A, B, x => x.id))
这篇关于JavaScript中的两个数组内部联接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!