Skip to main content

Posts

Showing posts from May, 2015

JavaScript: Counting Same Occurrences in an Array

For example We have an array: [2, "tea", 2, 1, 2, "tea", "bag", "bag", "bag", 1] And we wanna count the occurrence of every element (how many times it appears). Method There's a very long way to do that using bunch of loops. But then, I discovered a way using Object construction method. It's using just one forEach loop plus if-else conditional statement. Steps: Create an empty object. Loop through the array. While looping, for each of array element, create an object property of it (for that empty object). The value of that object property will then be filled with array of index where the element (object property) is found. Sounds hard, but not quite. Let's do it var occurrence = function (array) { "use strict"; var result = {}; if (array instanceof Array) { // Check if input is array. array.forEach(function (v, i) { if (!result[v]) { // Initial object pr...
Monkey Raptor uses cookies or biscuits 🍪 for analytics, functionality, and advertisements. More info in Privacy Policy