I have an array like [{type: car}, {type: van}, {type: truck}, {type: car}]
I need to return an array that looks like: [{type: car, count: 1}, {type: van, count: 1}, {type: truck, count: 1}, {type: car, count: 2}]
in the returned array, there is a new prop that stores what number of instance that value for type is. i.e. how many times has this value shown up in the array.
This is for an array that will be rendered and I want to include a number next to values that have duplicates in the array. I’m working with array methods reduce and map, maybe I will need a find function, I’m not sure
The main diff from the link for the possible duplicate and my question is that the linked question/answer results in an array with each unique value and a count of the duplicates whereas I would like my og array with an additional prop that is the number of times this value has shown up in the array. so the first instance of a value would be have count: 1, the second instance count: 2 and so on.
I’ve tried using a reduce function to give me a count of the duplicates for each value but now that I’m mapping through the original array I’m having trouble determining if i’m on the first, second, ect of that value. for example I can find if there are 3 of the current value i’m on in my array.map but I don’t know if its the first or second or third one in that array.
here is what I have:
let countArray = this.props.clauses.reduce((prev, cur) => {prev[cur.leaseClauseType] = (prev[cur.leaseClauseType] || 0) + 1; return prev; }, {}); this.props.clauses.map((c: AnyObject, index: number)=> { //Here i can append the count from countArray to each value but I'd like to know if its the first, second ect. of that value }
Advertisement
Answer
This can be quickly done using two loops:
const addCountProp = function (arr) { // to store number of instances for each type const typeMap = {}; for (let i = 0; i < arr.length; i++) { const elem = arr[i]; if (typeMap[elem.type] === undefined) typeMap[elem.type] = 0; typeMap[elem.type] += 1; } // add 'count' property to each element of the array for (let i = 0; i < arr.length; i++) { const elem = arr[i]; elem.count = typeMap[elem.type]; } return arr; };