美文网首页
求数组某个相同值的数字和

求数组某个相同值的数字和

作者: kelly_0416 | 来源:发表于2022-01-17 16:28 被阅读0次
    const list = [
      { unit: '瓶', count: 1 }, { unit: '瓶', count: 2 },
      { unit: '箱', count: 3 }, { unit: '箱', count: 4 },
      { unit: '盒', count: 5 }, { unit: '盒', count: 6 },
    ]
    
    let allKeys = []
    for (var value of list) {
      allKeys.push(value.unit)
    }
    const sameKeys = [...new Set(allKeys)]
    console.log("🚀 ~ file: 1.jsx ~ line 12 ~ sameKeys", sameKeys)
    
    const sameKeysCount = sameKeys.map(item => {
      return { unit: item, count: 0 }
    })
    
    for (var item of list) {
      const index = pros.findIndex((element) => element.unit === item.unit);
      sameKeysCount[index].count += item.count
    }
    
    console.log("🚀 ~ file: 1.jsx ~ line 17 ~ sameKeysCount", sameKeysCount)
    

    相关文章

      网友评论

          本文标题:求数组某个相同值的数字和

          本文链接:https://www.haomeiwen.com/subject/huichrtx.html