【问题标题】:Get item that is present in all arrays (Javascript)获取所有数组中存在的项目(Javascript)
【发布时间】:2021-06-24 10:06:36
【问题描述】:

我有一个包含一堆这样的数组的对象:

{
    names: [0, 1, 2],
    gender: [2, 5, 1],
    boolean: [7, 2, 1, 6]
}

如何获取所有数组中存在的值,在本例中为1

【问题讨论】:

  • 您可能需要遍历每个属性。
  • 似乎 2 也出现在所有数组中。这是否意味着它总是会选择第一个值?

标签: javascript node.js arrays object


【解决方案1】:

实现这一点的一种方法是获取所有键值的不同值,然后循环遍历这些值,检查每个键的数组是否存在该值。

const obj = {
    names: [0, 1, 2],
    gender: [2, 5, 1],
    boolean: [7, 2, 1, 6]
}

// [1] Get the object's keys
const keys = Object.keys(obj);

// [2] Get distinct values by combining all the key arrays.
const distinctValues = [...new Set(keys.reduce((all, curr) => {
   return all.concat(obj[curr]);
}, []))];

// [3] Filter the distinct values by checking each value against
//     the key's array
const presentInAll = distinctValues.filter((value) => {
   return keys.every((key) => obj[key].includes(value));
});

console.log(presentInAll);

【讨论】:

    【解决方案2】:

    我想我会添加另一个解决方案,它不会对原始数据制作任何临时副本,如果数据较大或内存管理很重要,这可能很有用。

    const data = {
        names: [0, 1, 2],
        gender: [2, 5, 1],
        boolean: [7, 2, 1, 6]
    };
    
    function findCommon(...arrays) {
        // sort arrays by length so we optimize and iterate first by the shortest array
        arrays.sort((a, b) => {
            return a.length - b.length;
        });
        let results = new Set();
        // for each item in the first array
        for (let item of arrays[0]) {
            // look in other arrays for this value
            let found = true;
            for (let i = 1; i < arrays.length; i++) {
                if (!arrays[i].includes(item)) {
                    found = false;
                    break;
                }
            }
            if (found) {
                results.add(item);
            }
        }
        return results;
    }
    
    let results = findCommon(data.names, data.gender, data.boolean);
    console.log(Array.from(results));

    【讨论】:

    • 非常感谢!我认为这是最好的解决方案,因为我将在大量数据上使用它。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-11
    • 2016-01-18
    • 1970-01-01
    • 2019-01-10
    • 2019-01-27
    • 1970-01-01
    • 2018-09-13
    相关资源
    最近更新 更多