过滤器阵列不在另一个阵列中 [英] Filter Array Not in Another Array

查看:20
本文介绍了过滤器阵列不在另一个阵列中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要根据另一个数组过滤一个数组.击倒中是否有 util 函数?否则我需要使用 javascript

Need to filter one array based on another array. Is there a util function in knock out ? else i need to go with javascript

第一:

var obj1 = [{
    "visible": "true",
    "id": 1
}, {
    "visible": "true",
    "id": 2
}, {
    "visible": "true",
    "id": 3
}, {
    "Name": "Test3",
    "id": 4
}];

第二:

var obj2 = [ 2,3]

现在我需要根据 obj2 过滤 obj1 并从 obj1 返回上面数据中不在 obj2 omitng 2,3 中的项目(比较对象 1 Id)

Now i need to filter obj1 based on obj2 and return items from obj1 that are not in obj2 omittng 2,3 in the above data (Comparison on object 1 Id)

输出:

[{
    "visible": "true",
    "id": 1
}, {
    "Name": "Test3",
    "id": 4
}];

推荐答案

您可以简单地使用 filter 运行 obj1 并使用 indexOfobj2 看看它是否存在.如果值不在数组中,indexOf 返回-1,当回调返回truefilter 包含该项目代码>.

You can simply run through obj1 using filter and use indexOf on obj2 to see if it exists. indexOf returns -1 if the value isn't in the array, and filter includes the item when the callback returns true.

var arr = obj1.filter(function(item){
  return obj2.indexOf(item.id) === -1;
});

<小时>

使用更新的 ES 语法和 API,它变得更简单:


With newer ES syntax and APIs, it becomes simpler:

const arr = obj1.filter(i => !obj2.includes(i.id))

这篇关于过滤器阵列不在另一个阵列中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆