【问题标题】:I do not want duplicate items to be rendered and to show in item_number how many duplicate items there are but the map does not do this [closed]我不希望呈现重复项目并在 item_number 中显示有多少重复项目,但地图不这样做 [关闭]
【发布时间】:2022-01-10 03:00:08
【问题描述】:
{arrOfProducts.map((item, index) => { 返回 ( ); }, 0)} ;

【问题讨论】:

  • 那么你的代码有什么问题?您是如何尝试调试问题的?
  • 我不希望重复项目被渲染并在 item_number 中显示有多少重复项目,但地图不这样做

标签: javascript arrays reactjs object developer-tools


【解决方案1】:

数组有方法reduce

arrOfProducts.reduce((acc, curr) => {
const foundedIndex = acc.findIndex(i => curr.id === i.id)
if(foundedIndex !== -1){
    const item = acc[foundedIndex]
    return [...acc.slice(0, foundedIndex), {...item, count: item.count+1}, ...acc.slice(foundedIndex+1)]
}
return [...acc, {...curr, count: 1}]
}, [])

【讨论】:

    猜你喜欢
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多