javascript - 如何比较一个数组中的元素到另一个数组中

标签 javascript arrays

如果 choices 数组中的任何 choice 对象在任何 results 数组中都找不到,则隐藏 choice 本例中的元素 {"choice": "f"}{"choice": "g"} 在这 3 个结果中都不可用,所以我需要隐藏它。我该怎么做?

{"choices":[
    {"choice": "a"},
    {"choice": "b"},
    {"choice": "c"},
    {"choice": "d"},
    {"choice": "e"},
    {"choice": "f"},
    {"choice": "g"}
],
"results":[
    {"result":["a", "b", "c"]},             
    {"result":["a", "b", "d"]},
    {"result":["a", "b", "e"]},

最佳答案

您可以从结果和过滤器选项中收集所有值。

var object = { choices: [{ choice: "a" }, { choice: "b" }, { choice: "c" }, { choice: "d" }, { choice: "e" }, { choice: "f" }, { choice: "g" }], results: [{ result: ["a", "b", "c"] }, { result: ["a", "b", "d"] }, { result: ["a", "b", "e"] }] },
    hash = Object.create(null),
    notIn = [];

object.results.forEach(function (a) {
    a.result.forEach(function (b) {
        hash[b] = true;
    });
});

notIn = object.choices.filter(function (a) {
    return !hash[a.choice];
});

console.log(notIn);
.as-console-wrapper { max-height: 100% !important; top: 0; }

ES6 与 Set

var object = { choices: [{ choice: "a" }, { choice: "b" }, { choice: "c" }, { choice: "d" }, { choice: "e" }, { choice: "f" }, { choice: "g" }], results: [{ result: ["a", "b", "c"] }, { result: ["a", "b", "d"] }, { result: ["a", "b", "e"] }] },
    results = object.results.reduce((s, a) => new Set([...s, ...a.result]), new Set),
    notIn = object.choices.filter(a => !results.has(a.choice));

console.log(notIn);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何比较一个数组中的元素到另一个数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42651740/

相关文章:

C编程: Delete specific value stored in Array

javascript - 判断字符串中的所有字母是否按字母顺序排列 JavaScript

javascript - 无法设置 null 错误的属性 'innerHTML'

javascript - StaticRouter 为 <Link> 标签呈现前导斜杠 [react-router 4.0.0]

javascript - jQuery Validation : $. data($ ('form' )[0], 'validator' ).settings 返回 undefined

javascript - 连接到 ng-model 的 Angular 数组值

php - 当数组存在时无法从数组中检索值

javascript - 针对 SocialEngine 4.x/Zend Framework 基于 level_id 的回显文本

javascript - jQueryeach() 只选择最后一个值

java - 在运行其他文件时使用另一个文件方法中的 java 变量