You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计React数组中相同key元素的出现次数

React中统计数组元素按key的出现次数

直接通过数组遍历结合累加器就能实现需求,以下是具体实现方案:

核心实现逻辑

利用Array.reduce遍历count数组,以item的key为唯一标识累加计数,同时结合useMemo做性能优化,避免每次渲染重复计算:

import { useState, useMemo } from 'react';

function CartComponent() {
  const [store, setStore] = useState([]);
  const [count, setCount] = useState([]);

  const addToCart = (item) => {
    setStore((currentItems) => [...currentItems, item]);
    setCount((prevCount) => [...prevCount, item]);
  };

  // 统计每个key对应的出现次数
  const itemCounts = useMemo(() => {
    return count.reduce((countObj, item) => {
      countObj[item.key] = (countObj[item.key] || 0) + 1;
      return countObj;
    }, {});
  }, [count]);

  return (
    <div>
      {/* 示例添加按钮 */}
      <button onClick={() => addToCart({ key: 'item1', text: '商品1' })}>添加商品1</button>
      <button onClick={() => addToCart({ key: 'item2', text: '商品2' })}>添加商品2</button>

      {/* 渲染统计结果 */}
      <div>
        <h3>商品购买次数统计</h3>
        {Object.entries(itemCounts).map(([itemKey, times]) => (
          <p key={itemKey}>{itemKey}: {times}次</p>
        ))}
      </div>
    </div>
  );
}

可选:仅统计store数组中存在的key

如果需要只统计count里和store中key匹配的项(当前逻辑下store和count同步添加,此场景可能非必需),可以先提取store的key集合再过滤:

const itemCounts = useMemo(() => {
  const validKeys = new Set(store.map(item => item.key));
  return count.reduce((countObj, item) => {
    if (validKeys.has(item.key)) {
      countObj[item.key] = (countObj[item.key] || 0) + 1;
    }
    return countObj;
  }, {});
}, [count, store]);

说明

  • reduce方法高效完成遍历与计数,最终返回一个{key: 次数}格式的对象
  • useMemo确保只有当count(或store,可选场景)变化时才重新计算统计结果,避免无意义的性能消耗
  • 用Object.entries将统计对象转为数组,方便React渲染列表

内容的提问来源于stack exchange,提问作者Gun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 03:10:43