Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding Mode in Javascript

I am having a difficult time with my code. I am working on a coderbyte problem and one part of the challenge is to find the mode of an array of numbers. So my first step I think is to create an object with numbers and their frequency. Here's what I have so far:

arr = [1,1,1,6,2,3,4];
mapping = {};
counter = 0
for(var i = 0;i < arr.length; i++){
    mapping[arr[i]] = 0;
       if(arr[i] == mapping[i.toString])
            mapping[i.toString] += 1
}
mapping

but this is giving me { '1': 0, '2': 0, '3': 0, '4': 0, '6': 0 }

Any ideas?

like image 778
theamateurdataanalyst Avatar asked Jan 19 '26 11:01

theamateurdataanalyst


1 Answers

This works better:

arr = [1,1,1,6,2,3,4];
mapping = {};
counter = 0
for(var i = 0;i < arr.length; i++){
    if (!mapping[arr[i]]) mapping[arr[i]] = 0;
    mapping[arr[i]] += 1
}

// mapping = {1: 3, 2:1, 3:1, 4:1, 6:1}
like image 108
Agnislav Avatar answered Jan 22 '26 00:01

Agnislav