How to make a generic reduce using a pattern

Viewed 28

I have the following pattern $.items[*].value

const map = $.items[*].value //it's just a string from JSON

Having this pattern, I need to make a generic reduce, which will work in the following way:

1 case: $.items[*].value

const sum = items.reduce((acc, item)=>{
   return acc + item[‘value’]
},0)

2 case: $.items[*].count

const sum = items.reduce((acc, item)=>{
   return acc + item[‘count’]
},0)

It would also be nice to be able to limit items in case there is a selection inside and not * But I'm not sure I know the best way to do it ( using indexes or condition instead of *), so I'll leave it as an optional.

3 case ( optional ): $.items[0, 3].value

const sum = items.reduce((acc, item, i)=>{
  if([0, 3].includes(i)) {
    return acc
   }
   return acc + item[‘value’]
},0)
0 Answers
Related