Siva Pradhan
Siva Pradhan

Reputation: 861

Count for same value in array of object

Suppose I have an array of object as:

const details = [{"book":"harry","part":1},{"book":"harry","part":2},{"book":"harry","part":3}, 
                 {"book":"lotr","part":1},{"book":"lotr","part":2},{"book":"lotr","part":3}]

I was able to get count of book with common name, by following method

const eachBookCount = details.reduce((acc, item) => {
        const key = item.book
        if (!acc.hasOwnProperty(key)) {
            acc[key] = 0
        }
        acc[key] += 1
        return acc
}, {})

This gives O/P: {harry: 3, lotr: 3}

But what I want to do is multiply each count with let's say a constant 2, with in same method that I used

So expected O/P is : {harry: 6, lotr: 6}

I'm confused on how can I multiply with constant 2 with in same method I used to count.

Let me know if anyone needs any further information.

Upvotes: 1

Views: 53

Answers (1)

Jabal Logian
Jabal Logian

Reputation: 2332

I think you can replace the counter (+1 for acc[key]) with the number you want for example 2

const eachBookCount = details.reduce((acc, item) => {
        const key = item.book
        if (!acc.hasOwnProperty(key)) {
            acc[key] = 0
        }
        
        const numberYouWant = 2 
        acc[key] += numberYouWant
 
        return acc
}, {})

Upvotes: 3

Related Questions