js数组对象

樊小烦
  • 65

有如下数组对象:

let A = [
          { id: 1, name: "张三", address: "北京" },
          { id: 2, name: "李四", address: "上海" },
          { id: 3, name: "张三", address: "杭州" },
          { id: 4, name: "王五", address: "深圳" },
          { id: 5, name: "李四", address: "厦门" },
          { id: 6, name: "张三", address: "广州" },
        ]

现在希望能根据name属性的值判断是否有重复,如果有就(保存)返回所有name值相同的对象并存入一个新数组中,如果没有重复则删除:如下:

[
          { id: 1, name: "张三", address: "北京" },
          { id: 2, name: "李四", address: "上海" },
          { id: 3, name: "张三", address: "杭州" },
          { id: 5, name: "李四", address: "厦门" },
          { id: 6, name: "张三", address: "广州" },
        ]

希望各位大佬能帮小弟看下,感谢!

回复
阅读 1.2k
3 个回答
扬帆启航
  • 3.3k
✓ 已被采纳
var A = [
          { id: 1, name: "张三", address: "北京" },
          { id: 2, name: "李四", address: "上海" },
          { id: 3, name: "张三", address: "杭州" },
          { id: 4, name: "王五", address: "深圳" },
          { id: 5, name: "李四", address: "厦门" },
          { id: 6, name: "张三", address: "广州" },
        ];
Object.values(A.reduce((acc,cur)=>((acc[cur.name]||(acc[cur.name]=[])).push(cur),acc),[])).filter(item=>item.length > 1).flat();

结果

[
  {
    "id": 1,
    "name": "张三",
    "address": "北京"
  },
  {
    "id": 3,
    "name": "张三",
    "address": "杭州"
  },
  {
    "id": 6,
    "name": "张三",
    "address": "广州"
  },
  {
    "id": 2,
    "name": "李四",
    "address": "上海"
  },
  {
    "id": 5,
    "name": "李四",
    "address": "厦门"
  }
]
  const arr = []
    const B = A.map(i => i.name)
    A.forEach(i => {
      if (B.filter(j => j === i.name).length > 1) arr.push(i)
    })
    console.log(arr);
const counters = {};
const newArr = [];

A.forEach(item => {
  if (!counters[item.name]) counters[item.name] = 1;
  else counters[item.name]++;
});

A.forEach(item => {
  if (counters[item.name] >= 2) newArr.push(item);
});
宣传栏