How to loop through two arrays of objects and get a new array with some data modified?

How to loop through two arrays of objects and get a new array with some data modified?

Arrays:

  const products = [
    {
      brand: 'Levis',
      category: 'Jeans',
    },
    {
      brand: 'Levis',
      category: 'Jeans',
    },
    {
      brand: 'Levis',
      category: 'Tees',
    },
  ];


  const categories = [
    {
      name: 'Jeans',
    },
    {
      name: 'Tees',
    },
  ];

Need new categories array like this with new prop productCount:

  const newCategories = [
    {
      name: 'Jeans',
      productCount: 2,
    },
    {
      name: 'Tees',
      productCount: 0,
    },
  ];

I tried this way but it doesn’t work:

  const newArr = categories.map((category) => {
    let count = 0;

    const index = products.findIndex((product) => category.name === product.category);

    if (index > -1) {
      return {
        ...category,
        productCount: count++,
      };
    }

    return {
      ...category,
      productCount: 0,
    };
  });

>Solution :

Increasing the count number will not in that case because it will always start with zero. Instead, you can use the filter() method to find the number of products with a specific category and assign this number to productCount attribute.

const products = [{
    brand: 'Levis',
    category: 'Jeans',
  },
  {
    brand: 'Levis',
    category: 'Jeans',
  },
  {
    brand: 'Levis',
    category: 'Tees',
  },
];


const categories = [{
    name: 'Jeans',
  },
  {
    name: 'Tees',
  },
];

const newArr = categories.map((category) => {
  const numberOfItems = products.filter((product) => category.name === product.category);

  return {
    ...category,
    productCount: numberOfItems.length,
  };
});

console.log(newArr)

Leave a Reply