Skip to main content

Posts

Showing posts from May, 2015

JavaScript: Counting Same Occurrences in an Array

Hi! For example, we have an array: [2, "tea", 2, 1, 2, "tea", "bag", "bag", "bag", 1] And we want to count the occurrence of every element in the array — how many times it appears. Method We can use Object construction method to achieve that. The steps: Create an empty object. Loop through the input array. While looping — for each of the array element — create an object property (key) of that. The value of that object property (key) will be an array of index(es) where the input element is found. Let's Go It goes as such: function occurrence(array) { var result = {}; if (array instanceof Array) { // Check if input is array. array.forEach(function (v, i) { if (!result[v]) { // Initial object property (key) creation. result[v] = [i]; // Assign an array for that property. } else { // Same occurrences found. ...
Monkey Raptor uses cookies for analytics, advertisements, and functionality. Privacy Policy