Reputation:
How can I get the most repeated value from an Array in javascript?
This is my array
var data = [
{ values: "Number of pips" },
{ values: 4 },
{ values: 4 },
{ values: 4 },
{ values: 5 },
{ values: 2 },
{ values: 6 },
{ values: 6 },
{ values: 5 }
];
The result should be 4
, how can I get this?
I have tried this, taken from Get the element with the highest occurrence in an array
function mode(array)
{
if(array.length == 0)
return null;
var modeMap = {};
var maxEl = array[0], maxCount = 1;
for(var i = 0; i < array.length; i++)
{
var el = array[i];
if(modeMap[el] == null)
modeMap[el] = 1;
else
modeMap[el]++;
if(modeMap[el] > maxCount)
{
maxEl = el;
maxCount = modeMap[el];
}
}
return maxEl;
}
but this is return 6, not 4
.
Upvotes: 1
Views: 2463
Reputation: 48465
The problem with your attempted code is that you do not have an array of numbers, you have an array of objects. If you want to count the most values
then you have to use that value, rather than the whole object.
In regards to the code you have attempted, you just need to change the following line:
var el = array[i].values;
Here is the full code:
function mode(array)
{
if(array.length == 0)
return null;
var modeMap = {};
var maxEl = array[0], maxCount = 1;
for(var i = 0; i < array.length; i++)
{
var el = array[i].values;// This is the change.
if(modeMap[el] == null)
modeMap[el] = 1;
else
modeMap[el]++;
if(modeMap[el] > maxCount)
{
maxEl = el;
maxCount = modeMap[el];
}
}
return maxEl;
}
Upvotes: 3
Reputation: 4906
I Got This
var arr= [{ values: "Number of pips" }, { values: 4 }, { values: 4 }, { values: 4 }, { values: 5 }, { values: 2 }, { values: 6 }, { values: 6 }, { values: 5 }];
var uniqs = {};
for(var i = 0; i < arr.length; i++) {
uniqs[arr[i].values] = (uniqs[arr[i].values] || 0) + 1;
}
var max = { val: arr[0], count: 1 };
for(var u in uniqs) {
if(max.count < uniqs[u]) { max = { val: u, count: uniqs[u] }; }
}
alert(max.val);
Upvotes: 2
Reputation: 15355
Upvotes: -1