簡體   English   中英

查找對象數組的所有常見元素-Javascript

[英]Find all common elements of an array of objects - Javascript

我的數據結構如下:

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

您可以將哈希表用於相同的命名對象,並將過濾器Options用於公共元素。

 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); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

您只需要為每個名稱保留數組的當前狀態,並在遇到該名稱時對其進行進一步過濾。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM