'I am trying to filter on date and reduce the response and do .push to my Data array. But i get error on push cannot assign numbers to strings

This is the the data[] that I want to do push on reduce.

const data = [{
    'Date': '', 
    'AssignedA': 0, 
    'ConsumedA': 0, 
    'AssignedB': 0, 
    'ConsumedB': 0, 
    'AssignedC': 0, 
    'ConsumedC': 0, 
    'AssignedD': 0, 
    'ConsumedD': 0, 
    'AssignedE': 0, 
    'ConsumedE': 0
  }];

    // Here I am trying to reduce using response from api
    const row = response.filter(
      feedDay => feedDay.VisitDate === feedDay.VisitDate
      ).reduce(
        (feeds, cow) => [
          feeds[0] + cow.AssignedFeedA,
          feeds[1] + cow.ConsumedFeedA,
          feeds[2] + cow.AssignedFeedB,
          feeds[3] + cow.ConsumedFeedB,
          feeds[4] + cow.AssignedFeedC,
          feeds[5] + cow.ConsumedFeedC,
          feeds[6] + cow.AssignedFeedD,
          feeds[7] + cow.ConsumedFeedD,
          feeds[8] + cow.AssignedFeedE,
          feeds[9] + cow.ConsumedFeedE
        ], []
      )
        
      data.push(row)

Full Code

function aggregateResults(response: FeedRation[], activeFeedTypes: boolean[], fmt: Formatter) {
  const uniqueDates = generateUniqueDates(response);
  const data: [string[], ...[string, ...number[]][]] = [
    ['Date', 'AssignedA', 'ConsumedA', 'AssignedB', 'ConsumedB', 'AssignedC', 'ConsumedC', 'AssignedD', 'ConsumedD', 'AssignedE', 'ConsumedE']
  ];

  for (const date of uniqueDates) {
    const row: [string, ...number[]] = [
      fmt(date).f,
      ...response.filter(
        feedDay => feedDay.VisitDate === date
      ).reduce(
        (feeds, cow) => [
          feeds[0] + cow.AssignedFeedA,
          feeds[1] + cow.ConsumedFeedA,
          feeds[2] + cow.AssignedFeedB,
          feeds[3] + cow.ConsumedFeedB,
          feeds[4] + cow.AssignedFeedC,
          feeds[5] + cow.ConsumedFeedC,
          feeds[6] + cow.AssignedFeedD,
          feeds[7] + cow.ConsumedFeedD,
          feeds[8] + cow.AssignedFeedE,
          feeds[9] + cow.ConsumedFeedE
        ], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
      )
    ];

    data.push(row);
  }

  // length === 1 because response from database is empty set and data is prepopulated with the header row
  if (data.length === 1) {
    data.push(['', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
  }

  return data.map(
    (weekData: any[]) => [
      weekData[0],
      ...activeFeedTypes.flatMap(
        (active, i) => ifActive(active, () => weekData.slice(i * 2 + 1, (i + 1) * 2 + 1))
      )
    ]
  );
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source