Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Count number of occurances in array [duplicate]

Tags:

jquery

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

like image 232
Corbin Spicer Avatar asked Mar 21 '14 11:03

Corbin Spicer


People also ask

How do you check if there are duplicates in an array Javascript?

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.


2 Answers

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}
like image 127
hsz Avatar answered Nov 04 '22 14:11

hsz


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

like image 40
Rajesh Dhiman Avatar answered Nov 04 '22 14:11

Rajesh Dhiman