代码之家  ›  专栏  ›  技术社区  ›  JdeMello

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

  •  0
  • JdeMello  · 技术社区  · 6 年前

    myData 这些元素属于 group B类 year 匹配那些在

    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}];
    

    [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 回复  |  直到 6 年前
        1
  •  1
  •   AsherMaximum    6 年前

    您已经完成了一半;现在您已经有了一个数组,其中包含了“A”组中的所有年份,您只需要检查“B”组中的年份是否在该数组中。你可以用 .includes() 为了这个。

    mySubset = myData.filter((d) => {return d.group == "B" && x.includes(d.year);});
    
        2
  •  1
  •   amrender singh    6 年前

    Set 其中包含了所有的年组 A

    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);
        3
  •  1
  •   Francis Leigh    6 年前

    通过做一个 getSubset()

    我还过滤掉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)