I’ve got some code which loops through an array of products, it records new categories found and also how many times a category is found:
const categoriesFound = (catArray) => {
let categories = {}
for (let i = 0; i < catArray.length; i++) {
let cat = catArray[i].toString()
let numberFound = categories[cat] = ++ categories[catArray[i]] || 1
}
return categories
}
let numberOfCats = categoriesFound(categoryNumbers);
console.log('number of categories:', numberOfCats);
Which returns this in the console and is what I want to extract for use:
I thought that would be the hard bit but I’m actually struggling to extract those keys and values and add them to new elements per item listed above.
I tried adding a .createElement()
adding the key and values for each loop and appending them to the right parent element, so it outputted:
<div class="categories">
<div class="category">beauty</div> <div class="">5</div>
<div class="category">fragrance</div> <div class="">5</div>
<div class="category">furniture</div> <div class="">5</div>
<div class="category">groceries</div> <div class="">27</div>
</div>
but then realised that was adding all duplicate categories and not just the merged category list and the number of times they are found.
I tried a for
and forEach
on the numberOfCats
to try and extract from the returned data but that fails stupendously.
So now I’m stuck trying to figure out a way of achieving the above and help would be grateful, thanks.
2
Answers
You can loop over the object and dynamically create elements
Your objective can easily be achieved by using a template string:
and placing that in a
.map()
loop: