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

时间:2017-03-07 15:08:54

标签: javascript arrays

如果在choice数组隐藏choices元素中找不到results数组中的任何choice对象{"choice": "f"}和{ {1}}在这3个结果中没有任何一个,所以我需要隐藏它。我该怎么做?

{"choice": "g"}

4 个答案:

答案 0 :(得分:2)

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

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; }

答案 1 :(得分:0)

我不确定您是否要求提供通用的实现方法,或者指出如何在javascript中实现它。我会选择一般的想法。您只需使用set存储所有可能的结果,然后遍历选项并检查每个选项是否在集合内。如果没有,你可以采取你想要的行动,无论这意味着什么。

答案 2 :(得分:0)

您可以对data.choices使用filter(),然后some()includes()检查结果数组中某些对象是否存在选择。

var data = {"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"]}]}

data.choices = data.choices.filter(function(o, i) {
  var check = data.results.some(e => e.result.includes(o.choice))
  return check;
})

console.log(data)

答案 3 :(得分:0)



var choices = {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"]}]},

    elems1 = choices.results.map(v => v.result).reduce((a,b) => a.concat(b)),
    filtered = [...new Set(elems1)];
    choices.choices = choices.choices.filter(v => filtered.some(c => c == v.choice) );
    console.log(choices);