javascript - 返回一个与另一个数组中的任何项目都不匹配的数组项目?

标签 javascript arrays sorting object

我有两个相同的对象数组。

然后,我将一个对象添加到随机索引处的数组之一:

Arr1 = [{ id: "a" }, { id: "b" }, { id: "c" }]

Arr2 = [{ id: "a" }, { id: "d" }, { id: "b" }, { id: "c" }]

我将如何比较两个数组,从 Arr2 中提取新对象并将该对象分配给常量?

这是我最大的努力:

const newPlan
if (state.plans.length !== data.allPlansJson.edges.length) {
    data.allPlansJson.edges.map(staticPlan => {
        state.plans.map(planInState => {
            planInState !== staticPlan && newPlan = staticPlan
        })
    })
}

还要添加更多上下文:

我正在从数组 data.allPlansJson.edges 获取对象并将它们传播到我的数据库集合中。然后,我获取所有这些对象并将它们放回到我的 redux 状态的数组中。

该函数用于检测何时有新对象添加到 data.allPlansJson.edges数组并执行一个 redux 操作,将该新对象发布到我的数据库集合中。

最佳答案

对于这个特定场景,为了仅获取新项目,您可以过滤掉原始项目中的任何点。

const arrA = [{ id: "a" }, { id: "b" }, { id: "c" }];
const arrB = [{ id: "a" }, { id: "d" }, { id: "b" }, { id: "c" }];

const newItems = arrB.filter(b => !arrA.some(a => a.id === b.id));

arrB.filter 循环调用箭头函数的 arrB。为了保留一个项目,我们在此回调中返回 true。为了删除一个项目,我们返回 false。

arrA.somearrA 上循环调用提供的箭头函数。如果任何项目返回 true,则该函数将解析 true。由于我们要匹配数组中找到的项目,因此我们在 arrA.some 之前添加 ! 以便查找找到的项目

您现在可以通过执行以下操作从 newItems 获取第一个项目

const [someConst] = newItems;
<小时/>

注意:这是一种单向搜索。如果arrA中有新的,它们将找不到

关于javascript - 返回一个与另一个数组中的任何项目都不匹配的数组项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57277603/

相关文章:

javascript - Typescript 认为响应数组是一个对象

javascript - AngularJS:从过滤器获取动态数组,然后将其用于 forEach 方法

javascript - 为什么我无法对 firebase 查询返回的日期数组进行排序?

c++ - 错误 : passing 'const T' as 'this' argument of 'bool T::operator<(T)' discards qualifiers

javascript - 如何在 React 中将所有数组项重新排序到特定索引?

javascript - Web API - 保留字?

javascript - 递归时Return(1)的作用是什么?

javascript - 提升导致 jQuery 中的问题

Java - 存储单个值和一条相应信息的最佳方式?

c++ - 关于 new[][] 和初始化数组中的类