1

描述:根据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}]]
12月5日提问
3 个回答
0

已采纳

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

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);
0
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)))], []);
0
var r = arr.map((currentValue)=>{
                return currentValue.filter(item => {return item.key == 2})
            })

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

撰写答案

推广链接