首页 > 解决方案 > 打印数组存在的名称

问题描述

我有这段代码:

var data = {
        sand: [['sun', 'moon', 'cool'], ['man', 'store', 'rose', 'big', 'you', 'sharp', 'low', 'high'], ['hot', 'cool', 'lip'], ['store', 'man', 'lip']],
        king: [['store', 'man', 'lip'], ['store', 'man', 'lip'], ['store', 'man', 'lip']],
        house: [['lip', 'store', 'hot', 'bed', 'you', 'low', 'run', 'high'], ['cool', 'sun', 'hot', 'big', 'sharp', 'low', 'run', 'high'], ['high', 'cool', 'moon', 'lip', 'man'], ['man', 'store', 'rose', 'big', 'you', 'sharp', 'low', 'high']],
        bow: [['lip', 'store', 'hot', 'bed', 'you', 'low', 'run', 'high'], ['bed', 'moon', 'lip'], ['low', 'cool', 'lip', 'man']],
        queen: [['cool', 'awe'], ['low', 'dad'], ['usa', 'cool', 'ita'], ['bed', 'glass', 'store', 'sal']],
}

我想打印所有['store', 'man', 'lip']存在的名称。所以,应该打印的是:沙,王。我怎样才能做到这一点?

标签: javascript

解决方案


您可以通过检查值与同一索引处的集合的值来为每个数组获取一个集合,以便与对象的键进行比较和过滤。

function getKeys(object, pattern) {
    return Object
        .keys(data)
        .filter(key => data[key].some(a =>
            a.length === pattern.length &&
            pattern.every((p, i) => a[i] === p)
        ));
}

var data = {
        sand: [['sun', 'moon', 'cool'], ['man', 'store', 'rose', 'big', 'you', 'sharp', 'low', 'high'], ['hot', 'cool', 'lip'], ['store', 'man', 'lip']],
        king: [['store', 'man', 'lip'], ['store', 'man', 'lip'], ['store', 'man', 'lip']],
        house: [['lip', 'store', 'hot', 'bed', 'you', 'low', 'run', 'high'], ['cool', 'sun', 'hot', 'big', 'sharp', 'low', 'run', 'high'], ['high', 'cool', 'moon', 'lip', 'man'], ['man', 'store', 'rose', 'big', 'you', 'sharp', 'low', 'high']],
        bow: [['lip', 'store', 'hot', 'bed', 'you', 'low', 'run', 'high'], ['bed', 'moon', 'lip'], ['low', 'cool', 'lip', 'man']],
        queen: [['cool', 'awe'], ['low', 'dad'], ['usa', 'cool', 'ita'], ['bed', 'glass', 'store', 'sal']],
    },
    pattern = ['store', 'man', 'lip'];

console.log(getKeys(data, pattern));


推荐阅读