Count repeated elements in an array

Hello, I wanted to know how to count repeated elements in an array and know how many times it is repeated

const colors = ["blue", "red", "blue", "yellow"];

One way of doing this is to create an object which will store the repeated elements and how many times they are repeated. Each object property would be the same as the unique array elements and the value of the property would be the total number of times the element has been seen. You would iterate through the array and check if the value of the element is already present in your object. If it is, then you would increase the value of the property by one. If it is not present, then you would add the value as the property and assign the property value 1.

Note: The object I describe above would also contain elements which are only present one time, so you would need remove any properties which did not have a value greater than 1.

1 Like