I have an array containing different types of vehicles like [{type: car}, {type: van}, {type: truck}, {type: car}]
My goal is to transform this array into one that includes a count for each type, like so: [{type: car, count: 1}, {type: van, count: 1}, {type: truck, count: 1}, {type: car, count: 2}]
In the final array, there should be a new property that indicates how many times each type appears in the original array.
This modification is needed because I will be rendering the array and want to display a number next to values that are duplicated. I am considering using array methods such as reduce and map, possibly even incorporating a find function.
The main difference between my question and a related link is that while the linked answer returns an array with unique values and their duplicate counts, I want to retain the original array structure but add a property indicating the occurrence number of each value.
So far, I attempted to use a reduce function to calculate the duplicates count for each value, but when mapping through the original array, I struggle to determine whether it's the first or subsequent instance of that value. For example, detecting if the current value has occurred multiple times without knowing its order within the array.
Here is what I have tried:
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 attach the count from countArray to each value, however, I aim to distinguish whether it's the initial or subsequent appearance of that value.
}