'Counting hours inside an array for a specific id

I am trying to count hours worked for an individual id dynamically. Currently, if I want to count the hours for id 1 for example I am having to hard code the id value and do the count. example below. I am using datatables so there will eventually be hundreds of rows

var array = [{id: 1, hours: 10},{id: 1, hours: 12}, {id: 2, hours: 6}, {id: 2, hours: 11} {id: 3, hours: 12}, {id: 3, hours: 8}]

 var array = dataTable.rows().data().toArray();
                    
                    array.filter((h) => {
                        
                        if (h.id == '1' && (count += h.hours) > 5) {
                            
                           'do something'
                        }
                        else {'do something'}
                    })

How do I count the hours of each 'id' dynamically without hard coding the id value thank you



Solution 1:[1]

Looks like you could use .map() here over filter I would wrap your filter / map into a function with an argument of id that way you can pass the ID everytime you call the function, without hard coding it.

var array = [{id: 1, hours: 10},{id: 1, hours: 12}, {id: 2, hours: 6}, {id: 2, hours: 11} {id: 3, hours: 12}, {id: 3, hours: 8}]


const countHours = (id) => {
  array.map(item => {
    if (item.id === id && item.hours > 5) {
        
      return 'do something'
   }
   else { return 'do something'}
  })
}

// call it like so...

countHours(1)

Solution 2:[2]

You could wrap this logic into a function that receives the id argument:

function hoursById (id) {
  let count = 0;
  const array = dataTable.rows().data().toArray();               
  array.forEach((h) => {                        
    if (h.id == id && (count += h.hours) > 5) {                            
      'do something'
    } else {
      'do something'}
  })
  return count;
}

Then you can invoke the function as

hoursById('1') // return count for id 1
hoursById('2') // return count for id 2

Solution 3:[3]

You could make a function to filter the array and use reduce to sum all the 'hours' values.

var arr = [{id: 1, hours: 10},{id: 1, hours: 12}, {id: 2, hours: 6}, {id: 2, hours: 11}, {id: 3, hours: 12}, {id: 3, hours: 8}]

function sumIdHours(id){
    var hourSum = arr.filter(x => x.id === id).reduce((a, b) => a + b.hours, 0)
    return hoursSum
}

//e.g.
sumIdHours(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
Solution 1
Solution 2 Kenzo
Solution 3