B中A与函数规划的相对补集(relative complement of A in B with functional programming)

编程入门 行业动态 更新时间:2024-10-27 04:27:59
B中A与函数规划的相对补集(relative complement of A in B with functional programming)

我必须检索仅存在于阵列B上但在阵列A上不存在的值。

从我的研究来看,它被称为:

B中A的相对补充

数组中的值可能不是原始的。我需要一个有效且功能性的应用程序来解决这个问题。 我找到了lodash _.without函数,但它只支持原始数组。

数组A:

[{ id: 1 }, { id:2 }]

数组B:

[{ id:2 }, { id:3 }]

结果应该是:

[{ id:3 }]

此对象是唯一存在于阵列B上的对象,但不存在于阵列A上。

I have to retrieve the values that exist only on Array B, but do not exist on Array A.

From my research, It is called:

relative complement of A in B

Values in the arrays may not be primitives.I need an efficient and functional apporach to this problem. I have found lodash _.without function, but it supports only array of primitive numbers.

Array A:

[{ id: 1 }, { id:2 }]

Array B:

[{ id:2 }, { id:3 }]

result should be:

[{ id:3 }]

this object is the only one who exist on Array B, but not on Array A.

最满意答案

你可以使用一个比较函数,它接受两个对象并检查id是否不相等。

var aa = [{ id: 1 }, { id: 2 }],
    bb = [{ id: 2 }, { id: 3 }],
    comparison = (a, b) => a.id !== b.id,
    result = bb.filter(b => aa.every(a => comparison(a, b)));

console.log(result); 
  
 

检查是否平等

var aa = [{ id: 1 }, { id: 2 }],
    bb = [{ id: 2 }, { id: 3 }],
    comparison = (a, b) => a.id === b.id,
    result = bb.filter(b => aa.every(a => !comparison(a, b)));

console.log(result); 
  
 

You could use a comparison function which takes two objects and check the id for unequalness.

var aa = [{ id: 1 }, { id: 2 }],
    bb = [{ id: 2 }, { id: 3 }],
    comparison = (a, b) => a.id !== b.id,
    result = bb.filter(b => aa.every(a => comparison(a, b)));

console.log(result); 
  
 

With a check for equalness

var aa = [{ id: 1 }, { id: 2 }],
    bb = [{ id: 2 }, { id: 3 }],
    comparison = (a, b) => a.id === b.id,
    result = bb.filter(b => aa.every(a => !comparison(a, b)));

console.log(result); 
  
 

更多推荐

本文发布于:2023-07-29 05:07:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1312618.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   relative   complement   functional   programming

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!