I would like to count the amount 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 would like to deduce
Item | Occurances -------------------- 1 | 2 3 | 1 4 | 2
Thanks in advance
You can try:
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);
conclusion:
Object { 1=2, 3=1, 4=2}
Live demo
Source: https://habr.com/ru/post/1532813/More articles:Creating multiple child accounts in AWS IAM - amazon-web-servicesIs there a way to search ALL mercurial commits for a particular string? - version-controlОбъект AttributeError 'tuple' не имеет атрибута 'get' - pythonPandas, build a new dataframe with a for loop - pythonPerformance Cypher SORT - neo4jSVG added to the DOM using javascript is not displayed. - javascriptRegex possesive quantifier - javaКак я могу сопоставить определенный формат ввода с помощью java.util.regex в java? - javaКак установить условие pdb break из исходного кода? - pythonCan we publish the value of the “Unverified radio station” button? - htmlAll Articles