js合并重复对象数组,并计算重复次数

  • Post author:
  • Post category:其他


准备一个原始对象数组

const array = [
  { id: 1 },
  { id: 2 },
  { id: 3 },
  { id: 1 },
  { id: 2 },
  { id: 3 }
]

方法一,reduce函数式编程

const arr = array.reduce((temp, item) => {
  const find = temp.find(i => i.id === item.id)
  find ? find.count++ : temp.push({ ...item, count: 1 })
  return temp
}, [])
console.log(arr) //[ { id: 1, count: 2 }, { id: 2, count: 2 }, { id: 3, count: 2 } ]

方法二,for循环,执行速度比reduce 快

const ids = []
const arr = []
for (const item of array) {
  if (!ids.includes(item.id)) {
    arr.push({ ...item, count: 1 })
    ids.push(item.id)
  } else {
    arr.find(a => a.id === item.id).count++
  }
}
console.log(arr) //[ { id: 1, count: 2 }, { id: 2, count: 2 }, { id: 3, count: 2 } ]



版权声明:本文为sundaoli_0原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。