I didn't find the simple example with JavaScript;
So I have an array with numbers and I need to show the number which is most repeated in array.
const getNumber = arr => {}
console.log(getNumber([1,2,5,2,8,5,2,10,1]))
I didn't find the simple example with JavaScript;
So I have an array with numbers and I need to show the number which is most repeated in array.
const getNumber = arr => {}
console.log(getNumber([1,2,5,2,8,5,2,10,1]))
const arr = [4,5,4,3,2,1,7,8,4];
const sortArr = (arr) => {
arr.sort();
var max=0,result,freq = 0;
for(var i=0; i < arr.length; i++){
if(arr[i]===arr[i+1]){
freq++;
}
else {
freq=0;
}
if(freq>max){
result = arr[i];
max = freq;
}
}
return result;
}
console.log(sortArr(arr)); //Output 4
Use Array#reduce to get an object with properties for all used numbers and their counts. Than use Object#entries to get out of this an array with the numbers and their counts and again use reduce to finde the number with the max-count. Get the number (first element) and return it.
const getNumber = arr => {
let counts = arr.reduce((acc, cur) => {
if (!acc[cur]) {
acc[cur] = 1;
} else {
acc[cur]++;
}
return acc;
},{});
return Object.entries(counts).reduce(([nr,max], [n, count]) => (count>max) ? [n, count] : [nr, max] )[0];
}
console.log(getNumber([1,2,5,2,8,5,2,10,1]));