Any native alternatives for going from:
const colorArray = ['red', 'green', 'green', 'blue', 'purple', 'red', 'red', 'black'];
to:
Object {
"red": 3,
"green": 2,
"blue": 1,
"purple": 1,
"black": 1
}
in javascript??
const colorArray = ['red', 'green', 'green', 'blue', 'purple', 'red', 'red', 'black'];
function categorizeUnique(array) {
const distinct_objects = {};
const length = array.length;
for(let i=0; i<length; i++) {
const distinct_objects_keys = Object.keys(distinct_objects);
const possible_index = distinct_objects_keys.indexOf(array[i]);
if(possible_index === -1) {
distinct_objects[array[i]] = 1;
} else {
distinct_objects[distinct_objects_keys[possible_index]]++;
}
}
return distinct_objects;
}
const result = categorizeUnique(colorArray);
console.log(result);
Thanks for your precious effort and time!!