Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading