js如何将一个二维数组按照相同值进行筛选?

描述:根据key值,保留所有key值相等的数组,其他的删除。

列子:var arr=[[{key:1,val:2},{key:2,val:3}], [{key:1,val:4},{key:2,val:2},{key:3,val:3}], [{key:1,val:2},{key:2,val:10},{key:3,val:12}]];
输出:[[{key:1,val:2},{key:2,val:3}], [{key:1,val:4},{key:2,val:2}], [{key:1,val:2},{key:2,val:10}]]
阅读 421
评论
    3 个回答
    • 580

    主要是不理解你这个实际的场景

    function getTheSame(arr) {
      return arr.reduce(function(a, b) {
        return a.filter(function(obj) {
          return include(b, obj.key);
        });
      });
    }
    function include(arr, value) {
      return arr.some(function(obj) {
        return obj.key === value;
      });
    }
    function getAllTheSame(arr, theSame) {
      return arr.map(function(arr1) {
        return arr1.filter(function(obj) {
          return include(theSame, obj.key);
        });
      });
    }
    const result = getTheSame(arr);
    const end = getAllTheSame(arr, result);
      • 1.6k
      var arr = [[{key: 1, val: 2}, {key: 2, val: 3}], [{key: 2, val: 2}, {key: 3, val: 3}], [{key: 1, val: 2}, {key: 2, val: 10}, {key: 3, val: 12}]];
      
      const filter = (key, arr) => arr.reduce((pre, list) => [...pre, ...(list.filter(it => it.key === key))], []);
      console.log(filter(2, arr));

      多个值传入keyList查询即可

      const filter = (keyList, arr) => arr.reduce((pre, list) => [...pre, ...(list.filter(it => keyList.includes(it.key)))], []);
        • 268
        var r = arr.map((currentValue)=>{
                        return currentValue.filter(item => {return item.key == 2})
                    })

        小老弟,你的描述有问题哈

          撰写回答

          登录后参与交流、获取后续更新提醒