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

如何在数组map中计算newBalance前后差值?解决reduce调用报错问题

Fixing the reduce is undefined Error & Calculating Balance Differences

Hey there! Let's work through this issue step by step.

Why You're Seeing the Error

The 'debt.reduce is undefined' error happens because you're trying to call reduce() on debt—but debt is a single object from your debtBalance array, not an array itself. The reduce() method only exists on arrays, so calling it on an object throws that error.

Solution 1: Precompute Differences with reduce

First, we'll use reduce() on the entire debtBalance array to create a new array that includes each entry's balance difference from the previous one. Then we can map over this new array to render the data:

// First, generate a new array with balance differences
const balanceHistoryWithDiff = debtBalance.reduce((accumulator, currentEntry, index) => {
  let diff = 0;
  // For the first entry, there's no previous value, so diff stays 0
  if (index > 0) {
    // Calculate difference: previous balance minus current balance (matches your original logic)
    diff = accumulator[index - 1].newBalance - currentEntry.newBalance;
  }
  // Add the current entry plus the computed diff to our accumulator
  accumulator.push({ ...currentEntry, diff });
  return accumulator;
}, []);

Then render it with map:

{balanceHistoryWithDiff.map((entry) => {
  return (
    <div className="transaction-history" key={entry._id}> {/* Use _id instead of index for stable keys */}
      <div className="transaction-history-entry">
        <p><Moment date={entry.balanceDate} format="Do MMM" /></p>
        <p>-£{entry.newBalance}</p>
        {/* Only show the difference for entries after the first one */}
        {entry.diff !== 0 && <p>Change: £{entry.diff}</p>}
      </div>
    </div>
  );
})}

Solution 2: Calculate Differences Directly in map

If you don't want to preprocess the array with reduce, you can calculate the difference on the fly while mapping by using the index to access the previous entry:

{debtBalance.map((debt, index) => {
  let diff = 0;
  if (index > 0) {
    const previousDebt = debtBalance[index - 1];
    diff = previousDebt.newBalance - debt.newBalance;
  }

  return (
    <div className="transaction-history" key={debt._id}>
      <div className="transaction-history-entry">
        <p><Moment date={debt.balanceDate} format="Do MMM" /></p>
        <p>-£{debt.newBalance}</p>
        {index !== 0 && <p>Change: £{diff}</p>}
      </div>
    </div>
  );
})}

Quick Note on React Keys

I swapped out using index as the React key for debt._id—this is a best practice because index keys can cause unexpected rendering issues if your array ever changes order or has items added/removed. Since you have a unique _id for each entry, it's the perfect stable key.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:28:02