Marko Nikolov
Marko Nikolov

Reputation: 835

Substituting filter with reduce for counting objects within range

I'm currently using this logic to filter out an array of objects within a date range and get a total count of the objects within that range.

const extractInRange = function (range, payload) {
    const start = new Date(range.startDate)
    const end = new Date(range.endDate)
    let dateRangeCount = 0
    payload.filter(item => {
        let date = new Date(item.createDate)
        if (date >= start && date <= end) {
            dateRangeCount++
        }
    })
    return dateRangeCount
} 

I want to substitute my filter logic with reduce specifically and I'm not sure how I should proceed.
I do know how to use reduce on arrays but the addition of start and end is causing some issues for me.

Upvotes: 0

Views: 19

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371138

You start with let dateRangeCount = 0, and you want iterations to conditionally increment that variable, so let that be your accumulator. Inside the callback, add to the accumulator if the conditions are met:

const extractInRange = function(range, payload) {
  const start = new Date(range.startDate);
  const end = new Date(range.endDate);
  return payload.reduce((dateRangeCount, item) => {
    const date = new Date(item.createDate);
    return dateRangeCount + (date >= start && date <= end);
  }, 0);
}

Here, the dateRangeCount will be a number, and (date >= start && date <= end) will be a boolean, so if the condition succeeds on an iteration, it'll return dateRangeCount + 1, else it'll return dateRangeCount. The return value will be the new accumulator (the dateRangeCount) for the next iteration.

Upvotes: 1

Related Questions