3

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?

theamateurdataanalyst
  • 2,794
  • 4
  • 38
  • 72

3 Answers3

1

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}
Agnislav
  • 299
  • 1
  • 9
  • try this jsbin: http://jsbin.com/wunohabifuso/1/edit . May be I misunderstand the task, please explain then. – Agnislav Sep 27 '14 at 21:27
  • can you explain `!mapping[arr[i]]` What has to be false – theamateurdataanalyst Sep 27 '14 at 21:42
  • Before incrementing a counter, we have to ensure that the property is exist. So, `!mapping[arr[i]]` does this check. More clear check can look like `if (mapping[arr[i]] === undefined)`. – Agnislav Sep 27 '14 at 21:47
  • Hm why isn't the if statement enclosed in brackets? – theamateurdataanalyst Sep 27 '14 at 22:13
  • Usually it's not recommended form. It can be used only for very simple and short statements. Please take a look [here](http://stackoverflow.com/questions/4797286/are-curly-braces-necessary-in-one-line-statements-in-javascript) and [here](http://stackoverflow.com/questions/2125066/is-it-bad-practice-to-use-an-if-statement-without-brackets) for more details. – Agnislav Sep 28 '14 at 01:40
1

If you directly want the modal array, you could use this as well.

const mode = arr => { if(arr.filter((x,index)=>arr.indexOf(x)==index).length == arr.length) return arr; else return mode(arr.sort((x,index)=>x-index).map((x,index)=>arr.indexOf(x)!=index ? x : null ).filter(x=>x!=null)) }

//mode([1,4,5,5,2,3,3,3,6,6,7,7,7,8,8]) //[3, 7]

Decoder
  • 11
  • 2
0

var data = [1,1,1,1,2,2,4,4,5,6];
var list = {};
data.forEach(function(e){
 if(typeof list[e] == "undefined"){
  list[e] = 1;
 }else{
  list[e] = list[e] + 1 ;
 }
});
console.log(list);
Atul Sharma
  • 9,397
  • 10
  • 38
  • 65