Skip to content

Instantly share code, notes, and snippets.

@riyadhalnur
Last active November 29, 2015 13:04
Show Gist options
  • Save riyadhalnur/430c46d74a1a96aa8cd2 to your computer and use it in GitHub Desktop.
Save riyadhalnur/430c46d74a1a96aa8cd2 to your computer and use it in GitHub Desktop.
Get the number of occurrences of every item in an array
// 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