Skip to content

Instantly share code, notes, and snippets.

@dmjcomdem
Last active January 9, 2018 21:50
Show Gist options
  • Save dmjcomdem/c1c94dc54fef33b42f729d62a3efd694 to your computer and use it in GitHub Desktop.
Save dmjcomdem/c1c94dc54fef33b42f729d62a3efd694 to your computer and use it in GitHub Desktop.
найти максимальное число в массиве и его количество повторений
let a = [1,2,3,4,5,6,3,4,6,6,3,7,8,8,8,4,5,7,4,6];
let object = a.reduce( (current, item) => {
current[item] = (current[item] || 0) + 1;
return current;
}, {})
let arrayValue = Object.keys(object).reduce( (current, item) => {
current.push( object[item] );
return current
}, [])
let maxKey = Math.max(...Object.keys(object));
let maxValue = Math.max(...arrayValue);
for(let key in object) {
if(key == maxKey) {
console.log(`Max value: ${key}, repeat: ${object[key]}`)
}
if(object[key] == maxValue) {
console.log(`Max repeat: ${object[key]}, value: ${key}`)
}
}
// Max repeat: 4, value: 4
// Max repeat: 4, value: 6
// Max value : 8, repeat: 3
uniqueCount = ["a", "b", "c", "d", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a", "a", "a", "a", "a"];
let objectKeyCountDuplicate = (arr) => arr.reduce((acc, item) => ((acc[item] = (acc[item] || 0) + 1), acc), {});
let getObjectValue = (arr) => Object.keys(arr).reduce((acc, item) => ((acc = acc.concat(arr[item])), acc), [])
var countDupl = objectKeyCountDuplicate(uniqueCount)
/**
* {
* "a": 7, // Max repeat symbol
* "b": 2,
* "c": 2,
* "d": 2,
* "e": 2,
* "f": 1,
* "g": 1,
* "h": 3
* }
*/
let valueDubl = getObjectValue(countDupl); // [7, 2, 2, 2, 2, 1, 1, 3]
objectKeyCountDuplicate(valueDubl)
/**
* {
* "1": 2,
* "2": 4, // 2 Max count dubl list in array
* "3": 1,
* "7": 1
* }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment