【问题标题】:Javascript - compare two arrays with filter as efficient as possibleJavascript - 使用过滤器尽可能有效地比较两个数组
【发布时间】:2020-11-23 01:41:30
【问题描述】:

我想用filter 尽可能高效地比较两个数组,并且尽可能地描述性。

我确信一定有一个不错的方法可以做到这一点,而无需求助于forEach,但我终其一生都找不到它,有人能帮助我摆脱痛苦吗?

场景

mainList array
id : 1, name : 'foo', categories : ["c1","c2","c3"]
id : 2, name : 'bar', categories : ["c1","c4","c5"]

userSelectListNames 数组“foo”

userSelectListCats 数组 "c1","c4"

过滤 mainList 类别 - 这是我卡住的地方

return mainList.filter(item => userSelectListCats.includes(item.categories));

如果他选择“c1”和“c4”或“c1”,我希望用户查看这两条记录 如果他选择“c4”和“c5”,则只有最后一个 但是我在尝试时感到非常困惑......

我最好的两次尝试..

return mainList.categories.filter(item => userSelectListCats.includes(item));

但它返回类别,而不是 mainList。

return mainList.filter(item => mainList.categories.filter(item2 => userSelectListCats.includes(item2)));

我确信一定有一个很好的方法可以做到这一点,而无需诉诸 forEach,但对于我的一生,我找不到它,有人能帮助我摆脱痛苦吗?

【问题讨论】:

  • 感谢 hev1 - 漂亮的解决方案!

标签: javascript arrays filter include


【解决方案1】:

您可以将Array#filterArray#some 一起使用。

const arr = [{id : 1, name : 'foo', categories : ["c1","c2","c3"]}, {id : 2, name : 'bar', categories : ["c1","c4","c5"]}];
const userSelectListCats = ["c1", "c4"];
const res = arr.filter(({categories})=>
   userSelectListCats.some(x => categories.includes(x)));
console.log(res);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-10
    • 1970-01-01
    • 2020-07-03
    • 2015-08-04
    • 2021-08-06
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多