Last active
November 29, 2015 13:04
-
-
Save riyadhalnur/430c46d74a1a96aa8cd2 to your computer and use it in GitHub Desktop.
Get the number of occurrences of every item in an array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// sample -> [ 1, 2, 1, 'a', [ 'd', 5, 6 ], 'A', 2, 'b', 1, 'd' ]; | |
// result -> { 1: 3, 2: 2, a: 1...} | |
function flattenArray (arr, result) { | |
result = result || []; | |
for (var i = 0; i < arr.length; i++) { | |
if (Array.isArray(arr[i])) { | |
flattenArray(arr[i], result); | |
} else { | |
result.push(arr[i]); | |
} | |
} | |
return result; | |
}; | |
var uniqueValues = flattenArray(arr).reduce(function (prev, cur) { | |
if (Object.keys(prev[cur]) === undefined) { | |
prev[cur] = 1; | |
} else { | |
prev[cur] += 1; | |
} | |
return prev; | |
}, {}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment