I'd like to count the number of each element in my array
Example:
var basketItems = ['1','3','1','4','4'];
jQuery.each(basketItems, function(key,value) {
// Go through each element and tell me how many times it occurs, output this and remove duplicates
}
I'd then like to output
Item | Occurances
--------------------
1 | 2
3 | 1
4 | 2
Thanks in advance
To check if an array contains duplicates: Use the Array. some() method to iterate over the array. Check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence. If the condition is met, then the array contains duplicates.
You can try with:
var basketItems = ['1','3','1','4','4'],
counts = {};
jQuery.each(basketItems, function(key,value) {
if (!counts.hasOwnProperty(value)) {
counts[value] = 1;
} else {
counts[value]++;
}
});
Result:
Object {1: 2, 3: 1, 4: 2}
Try
var basketItems = ['1','3','1','4','4'];
var returnObj = {};
$.each(basketItems, function(key,value) {
var numOccr = $.grep(basketItems, function (elem) {
return elem === value;
}).length;
returnObj[value] = numOccr
});
console.log(returnObj);
output:
Object { 1=2, 3=1, 4=2}
Live Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With