How do I get the length of duplicate object in an array

Hi there, is there a way I can get the length/count of duplicate object in my array

const arr = [
{id: 1,  name: "Cotton Jacket"},
{id: 1,  name: "Cotton Jacket"},
{id: 1,  name: "Cotton Jacket"},
{id: 2,  name: "Women Short Sleeves"},
{id: 2,  name: "Women Short Sleeves"},

For context, I’m working on an Ecommerce website and I need to get the unique quantity of each items added to the cart.

If there is a better way to implement this logic, pls let me know

If I understand, you want a function like:

const getDuplicateCount(arr, id) {}

and it will return a number?

That should be pretty easy to implement with a loop and a counter or using a reduce method if you want to get fancier. If you know the array will be sorted (like in your example) you might be able to optimize it a bit.

If i have to tackle the problem into pieces, id first prolly try to create a function which compare two objects, think how i would do that. One way would be to use some object method like object.entries() and compare the results, or loop thought one object keys, look if the other object has the key and if so, check if the values are equal. Another way to compare two objects would be to use the JSON.stringify() method, which would turn an object into a string and its easier to compare two strings for equality.
Then, you need to loop throught the array of objects, add each unique object in some sort of record, where you count how many times you’ve encountered that object.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.