从匹配数组的嵌套数组中获取名称 [英] Getting name from nesting arrays from matching arrays

查看:57
本文介绍了从匹配数组的嵌套数组中获取名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些数组,如果它们包含相似的值,我想返回这些数组的名称。

I have some arrays, and if they contain similar values, I would like to return the name of those arrays.



    var x = {
      "food": ['bacon', 'cheese', 'bread', 'tomato'],
      "utilities": ['plates', 'forks', 'spatulas'],
      "guests": ['john', 'matt', 'bill']
    },
    y = ['bacon', 'tomato', 'forks'];

我的变量 x ,它有多个数组,名称为 food ,或 utilities ,或来宾。所有 y 包含的,是某些值在 x 变量中的某些数组中是相同的。我需要返回包含 bacon tomato forks <的数组的名称/ code>在他们的数组中。所以对于这个例子,我需要返回: [food,utilities]

I have my variable x, and it has multiple arrays, with a name either food, or utilities, or guests. All that y contains, is some values that are the same within some of those arrays in the variable of x. I need to return the name of the arrays that contain bacon,tomato, and forks in their arrays. So for this example, I need to return: ["food", "utilities"].



    function getContainerName(obj, values) {
      return Object.keys(obj).find(function(key) {
        return values.every(value => obj[key].find(function(elem) {
          return elem === value;
        }));
      });
    }
    console.log(getContainerName(x, y));

当通过此函数抛出它们时,我收到错误 ******* ** 。我怎么去拿一个 [食物,实用程序] 的返回数组?

When throwing them through this function, I get an error *********. How may I go and get a returned array of ["food", "utilities"]?

推荐答案

Object.keys 上的简单 reduce()将完成工作

var x = {
    "food": ['bacon', 'cheese', 'bread', 'tomato'],
    "utilities": ['plates', 'forks', 'spatulas'],
    "guests": ['john', 'matt', 'bill']
  },
  y = ['bacon', 'tomato', 'forks'];

let res = Object.keys(x).reduce((a, b) => {
  if (x[b].some(v => y.includes(v))) a.push(b);
  return a;
}, []);

console.log(res);

对于你的评论 - 使用var和普通函数:

For your comment - with var and normal function:

var res = Object.keys(x).reduce(function (a, b) {
    if (x[b].some(function (v) {
            return y.indexOf(v) !== -1;
        })) a.push(b);
    return a;
}, []);

这篇关于从匹配数组的嵌套数组中获取名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆