通过匹配值数组来子集javascript对象文字

时间:2018-09-05 19:35:42

标签: javascript filter

我需要用属于myData B 的那些元素和group匹配year中的元素的子元素group来子集答:

var myData = [{"year":1,"group":"A","value":0.1},
 {"year":2,"group":"A","value":0.2},
 {"year":3,"group":"A","value":0.2},
 {"year":4,"group":"A","value":0.1},
 {"year":5,"group":"A","value":0.1},
 {"year":1,"group":"B","value":0.1},
 {"year":2,"group":"B","value":0.2},
 {"year":3,"group":"B","value":0.2},
 {"year":4,"group":"B","value":0.2},
 {"year":5,"group":"B","value":0.9},
 {"year":6,"group":"B","value":0.1}] ;

我可以使用.filter()获得所需的输出:

mySubset = myData.filter((d) => {return d.group == "B" && d.year < 6;});

导致:

[{"year":1,"group":"B","value":0.1},
  {"year":2,"group":"B","value":0.2},
  {"year":3,"group":"B","value":0.2},
  {"year":4,"group":"B","value":0.2},
  {"year":5,"group":"B","value":0.9}];

但这不是理想的。我想要一个通用的通用解决方案,该解决方案不依赖于“手动”输入最大值(6)。另外,year可能不是序列(例如[2, 1, 4, 5])。

基本上,障碍位于条件(d.year < 6)的第二部分。我需要与以下值匹配的东西:

let x = []

for(i = 0; i < myData.filter((d) => {return d.group == "A";}).length; i++){
    x.push(myData[i].year);
}

谢谢!

3 个答案:

答案 0 :(得分:1)

您首先可以创建一个Set,其中包含组A的所有年份,然后可以从数组中过滤出元素(如果该集合具有Year Year且该组是B,则可以添加)到结果):

var myData = [{"year":1,"group":"A","value":0.1}, {"year":2,"group":"A","value":0.2}, {"year":3,"group":"A","value":0.2}, {"year":4,"group":"A","value":0.1}, {"year":5,"group":"A","value":0.1}, {"year":1,"group":"B","value":0.1}, {"year":2,"group":"B","value":0.2}, {"year":3,"group":"B","value":0.2}, {"year":4,"group":"B","value":0.2}, {"year":5,"group":"B","value":0.9}, {"year":6,"group":"B","value":0.1}];

let set = new Set(myData.filter(e=>e.group =="A").map(e=>e.year));

let result = myData.filter(e=> e.group =="B" && set.has(e.year));

console.log(result);

答案 1 :(得分:1)

你在那儿;现在您已经有了“ A”组中所有年份的数组,您只需要检查“ B”组中的年份是否在该数组中。您可以为此使用.includes()

mySubset = myData.filter((d) => {return d.group == "B" && x.includes(d.year);});

答案 2 :(得分:1)

通过创建getSubset()函数,您可以将所需的组和年份作为参数传递(感谢@mhodges)

我还会过滤出yearGroups数组中所有可能为空的数组,以防年份不匹配任何内容

let myData = [
 {"year":1,"group":"A","value":0.1},
 {"year":2,"group":"A","value":0.2},
 {"year":3,"group":"A","value":0.2},
 {"year":4,"group":"A","value":0.1},
 {"year":5,"group":"A","value":0.1},
 {"year":1,"group":"B","value":0.1},
 {"year":2,"group":"B","value":0.2},
 {"year":3,"group":"B","value":0.2},
 {"year":4,"group":"B","value":0.2},
 {"year":5,"group":"B","value":0.9},
 {"year":6,"group":"B","value":0.1}
]


let getSubsets = (group = 'B', year = 6) => myData.filter(d => d.group == group && d.year < year)

console.log(getSubsets())

console.log(getSubsets('A', 4))

let yearGroups = [1,2,3,4,5].map(y => getSubsets('B', y)).filter(a => !!a.length)

console.log(yearGroups)