How can i count the number of identical objects by keys in an array? [closed]

I have an array of objects:

[
  { appleID: 13, bananaID: 55 },
  { appleID: 24, bananaID: 13}, 
  { appleID: 97, bananaID: 13},
  { appleID: 13, bananaID: 55 }
]

The result should look like this:

[
  { appleID: 13, bananaID: 55, count: 2 },
  { appleID: 24, bananaID: 13, count: 1}, 
  { appleID: 97, bananaID: 13, count: 1}
]

Count the number of identical elements by element === appleID && element === bananaID

Answer

const data = [
  { appleID: 13, bananaID: 55 },
  { appleID: 24, bananaID: 13}, 
  { appleID: 97, bananaID: 13},
  { appleID: 13, bananaID: 55 }
]

function countNum(arr){
    return arr.reduce((pre, item) => {
        const hasItem = pre.find(subItem => subItem.appleID === item.appleID && subItem.bananaID === item.bananaID)
        if(hasItem){
            hasItem.count++
        }else{
            pre.push({...item, count: 1})
        }
        return pre
    }, [])
}

console.log(countNum(data))

like this

function countNum(arr){
    return arr.reduce((pre, item) => {
        const hasItem = pre.find(subItem => subItem.appleID === item.appleID && subItem.bananaID === item.bananaID)
        if(hasItem){
            hasItem.count++
        }else{
            pre.push({...item, count: 1})
        }
        return pre
    }, [])
}

Leave a Reply

Your email address will not be published. Required fields are marked *