skip to Main Content

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.

2

Answers


  1. You can loop over the object and dynamically create elements

    const obj = {
      beauty: 5,
      fragrance: 5,
      furniture: 5,
      groceries: 27
    }
    
    function test() {
    
      const template = document.createDocumentFragment();
      for (const keys in obj) {
        const divElement = document.createElement('div');
        divElement.classList.add('category');
        const catName = document.createElement('span');
        const catCount = document.createElement('span');
        catName.innerText = keys;
        catCount.innerText = obj[keys];
        divElement.appendChild(catName);
        divElement.appendChild(catCount);
        template.appendChild(divElement);
      }
    
      return template;
    };
    document.getElementById('categories').appendChild(test())
    <div id="categories"></div>
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search