Search code examples
javascriptarraysloopscreateelement

Extracting values from array and adding them to new elements


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:

Array returned in the console log

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.


Solution

  • Your objective can easily be achieved by using a template string:

    `<div class="category">${k}</div> <div class="count">${v}</div>`
    

    and placing that in a .map() loop:

    const cats={beauty: 5,fragrances: 5,furniture: 5,groceries: 27,"home-decoration": 5,"kitchen-accessories": 30,laptops: 5,"mens-shirts": 5,"mens-shoes": 5,"mens-watches": 6,"mobile-accessories": 14,motorcycle: 5,"skin-care": 3,smartphones: 16,"sports-accessories": 17,sunglasses: 5,tablets: 3,tops: 5,vehicle: 5,"womens-bags": 5,"womens-dresses": 5,"womens-jewellery": 3,"womens-shoes": 5,"womens-watches": 5};
    
    document.querySelector(".categories").innerHTML=Object.entries(cats).map(([k,v])=>`<div class="category">${k}</div> <div class="count">${v}</div>`).join("<br>\n");
    div.category,div.count {display:inline}
    <div class="categories"></div>