如何从result1中返回不在result2数组中的对象数组?

时间:2019-11-02 00:00:00

标签: javascript ecmascript-6

如何比较两个数组,以便它们返回不匹配的对象数组。上面的条目向我返回了一个在另一个对象中的对象数组。如何从result1返回不在result2数组中的对象数组?

let result = result1.filter(o1 => result2.some(o2 => o1.id === o2.id));

此处演示:https://stackblitz.com/edit/js-qavyib

var result1 = [
    {id:1, name:'Sandra', type:'user', username:'sandra'},
    {id:2, name:'John', type:'admin', username:'johnny2'},
    {id:3, name:'Peter', type:'user', username:'pete'},
    {id:4, name:'Bobby', type:'user', username:'be_bob'}
];

var result2 = [
    {id:2, name:'John', email:'johnny@example.com'},
    {id:4, name:'Bobby', email:'bobby@example.com'}
];

let result = result1.filter(o1 => result2.some(o2 => o1.id === o2.id));

console.log(result);

/*
  0: Object
  id: 2
  name: "John"
  type: "admin"
  username: "johnny2"
  1: Object
  id: 4
  name: "Bobby"
  type: "user"
  username: "be_bob"*/

4 个答案:

答案 0 :(得分:4)

检查0.592922148,0.821504176,1.174129731 中的.every项没有相等的result2

id

答案 1 :(得分:2)

您在正确的轨道上。

2019年,现代方法是使用filter()

要比较两个数组并返回差值,您需要使用!not)运算符。

工作示例:

var result1 = [
    {id:1, name:'Sandra', type:'user', username:'sandra'},
    {id:2, name:'John', type:'admin', username:'johnny2'},
    {id:3, name:'Peter', type:'user', username:'pete'},
    {id:4, name:'Bobby', type:'user', username:'be_bob'}
];

var result2 = [
    {id:2, name:'John', email:'johnny@example.com'},
    {id:4, name:'Bobby', email:'bobby@example.com'}
];

let difference = result1.filter(({ id: id1 }) => !result2.some(({ id: id2 }) => id2 === id1));

console.log(difference);

答案 2 :(得分:2)

您可以对问题进行抽象处理,以编写一个接受谓词的函数,该谓词将告诉您两个值是否相等,然后将该常规函数与简单的(x, y) => x.id == y.id一起使用,以获取可以找到与您不同的函数正在寻找。像这样:

const diff = (pred) => (xs, ys) => 
  xs.filter(x => !(ys.some(y => pred(x, y))))

const diffById = diff ((x, y) => x.id === y.id) 

const result1 = [{id:1, name:'Sandra', type:'user', username:'sandra'}, {id:2, name:'John', type:'admin', username:'johnny2'}, {id:3, name:'Peter', type:'user', username:'pete'}, {id:4, name:'Bobby', type:'user', username:'be_bob'}]
const result2 = [{id:2, name:'John', type:'admin', username:'johnny2'}, {id:4, name:'Bobby', type:'user', username:'be_bob'}]

console.log (
  diffById (result1, result2)
)

答案 3 :(得分:1)

使用Ramda的单线解决方案,请尝试here或以下版本:

R.difference(result1, result2);

注意:此解决方案不仅检查一个属性,例如id,它检查所有道具是否相等。

const result1 = [
{id:1, name:'Sandra', type:'user', username:'sandra'},
{id:2, name:'John', type:'admin', username:'johnny2'},
{id:3, name:'Peter', type:'user', username:'pete'},
{id:4, name:'Bobby', type:'user', username:'be_bob'}
];

const result2 = [
{id:2, name:'John', type:'admin', username:'johnny2'},
{id:4, name:'Bobby', type:'user', username:'be_bob'}
];

const difference = R.difference(result1, result2);
console.log(difference);
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>