Home number of times that condition is true [javascript]

# number of times that condition is true [javascript]

fredericopimpao
1#
fredericopimpao Published in 2018-01-11 03:38:55Z
 This is probably a really noob question. I tried to search but probably i´m not asking google the right words. What i want to get is the number of times that the: -number 3 exist -number 2 exist -number 43 exist I could do it manually if the array has a fixed values, but the problem is that the array will be changing a lot, with completely different numbers. i will leave a img here if the text is not explicit enough :D var a = [2,3,3,3,2,43]; var t = [...new Set(a)]; for ( var k = 0, l = t.length; k < l; k ++ ) { for ( var i = 0, l = a.length; i < l; i ++ ) { if (a[i] == t[k]) { console.log(k); } }; };
Lewis
2#
 You can try this code. Basically, you just need to loop through the array of numbers then count the occurrences. let counts = {}; let nums = [2,3,3,3,2,43]; for(let num of nums) { counts[num] = (counts[num] || 0) + 1; } console.log(counts);
 Thank you for the answer. Work perfectly. I just changed the console.log line. so if somebody come here they get 100% what i want. Thank a lot Lewis let counts = {}; let nums = [2,3,3,3,2,43]; for(let num of nums) { counts[num] = (counts[num] || 0) + 1; } console.log(Object.values(counts));