查找对象数组的所有常见元素 - Javascript

时间:2018-01-14 16:23:20

标签: javascript arrays object

我的数据结构如下:

var Items = [{"Name":"type1","Options":[1,2,5]},{"Name":"type2","Options":[1,2]},{"Name":"type1","Options":[2,5]}];

我对javascript很新,但我想弄清楚与每种名称类型相关的常见选项。

Items数组中的元素数是任意的。所以我可以举40例。

上述数据的预期输出为

CommonOptions = [{"Name":"type1","Options":[2,5]},{"Name":"type2","Options":[1,2]}];

因为2和5对于名称为type1的所有元素都是通用的,而1,2对于名称为type2的元素的所有元素都是通用的。我不知道如何正确访问数据。

这是我的目标。如果有人能指引我朝着正确的方向前进,我真的很感激。

var Items = [{
  "Name": "type1",
  "Options": [1, 2, 5]
}, {
  "Name": "type2",
  "Options": [1, 2]
}, {
  "Name": "type1",
  "Options": [2, 5]
}];
//Define the Common Options Array as the first options and associated name
var CommonOptions = [];
CommonOptions.push(Items[0]);

//the first item is already in the common options array so start at 1
for (var i = 1, iLen = Items.length - 1; i < iLen; i++) {
  for (var j = 0, cLen = CommonOptions.length; j < cLen; j++) {

    //add all unique by name options to common options array
    if (CommonOptions[j].Name.indexOf(Items[i].Name) === -1) {
      //item name is not in the common options array
      //add item to common options array
      CommonOptions.push(Items[i]);
    } else {
      //item name is in the common options array
      // if it is in the common options array then check each Option in the Option array against the common options of that name
      //CommonOptions[j].Options.indexOf(Items[i].Options)===-1
    }
  }
}
console.log(CommonOptions);

2 个答案:

答案 0 :(得分:0)

您可以对相同的命名对象使用哈希表,并对公共元素过滤Options

&#13;
&#13;
var items = [{ Name: "type1", Options: [1, 2, 5] }, { Name: "type2", Options: [1, 2] }, { Name: "type1", Options: [2, 5] }],
    hash = Object.create(null),
    common = items.reduce(function (r, o) {
        if (hash[o.Name]) {
            hash[o.Name].Options = hash[o.Name].Options.filter(function (v) {
                return o.Options.indexOf(v) !== -1;
            });
        } else {
            hash[o.Name] = { Name: o.Name, Options: o.Options.slice() };
            r.push(hash[o.Name]);
        }
        return r;
    }, []);

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

答案 1 :(得分:0)

您只需要为每个名称分隔数组的当前状态,并在遇到该名称时进一步过滤它。

&#13;
&#13;
const Items = [{"Name":"type1","Options":[1,2,5]},{"Name":"type2","Options":[1,2]},{"Name":"type1","Options":[2,5]}];

const m = Items.reduce((m, o) => {
  const a = m.get(o.Name);
  return m.set(o.Name, a ? a.filter(n => o.Options.includes(n)) : o.Options);
}, new Map());

const res = Array.from(m.entries(), ([Name, Options]) => ({Name, Options}));
console.log(res);
&#13;
&#13;
&#13;