I know how to do this in SQL lol, but not in JS.
If you have an array like this = var arrayRepeatedNumbers = [100,100, 20, 10,10,10]
How can you group them by amount?
Example:
var arrayNonRepeated = [Hundreds: 2, Twenties: 1, Tens: 3]
I know how to do this in SQL lol, but not in JS.
If you have an array like this = var arrayRepeatedNumbers = [100,100, 20, 10,10,10]
How can you group them by amount?
Example:
var arrayNonRepeated = [Hundreds: 2, Twenties: 1, Tens: 3]
(() => {
// add definitions in here.
const dictionary = new Map([
[10, 'Tens'],
[20, 'Twenties'],
[100, 'Hundreds']
]);
// your test values
const arrayRepeatedNumbers = [
100, 100, 20, 10, 10
];
// will hold a map of repeating values
const mapNonRepeated = new Map();
arrayRepeatedNumbers.forEach((number) => {
// stores dictionary key
const dictionaryKey = dictionary.get(number);
// checks if key exists in your final map
const keyExists = mapNonRepeated.has(dictionaryKey);
// if key exists in map add one to it
if (keyExists){
let value = mapNonRepeated.get(dictionaryKey);
mapNonRepeated.set(dictionaryKey, value = value + 1);
return;
}
// otherwise set it to 1
mapNonRepeated.set(dictionaryKey, 1);
});
console.log(mapNonRepeated);
//Map(3) {"Hundreds" => 2, "Twenties" => 1, "Tens" => 2}
// Map has some advantages over the standard Object.
})();