Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
72
rated 0 times [  75] [ 3]  / answers: 1 / hits: 5405  / 10 Years ago, sat, september 27, 2014, 12:00:00

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?


More From » arrays

 Answers
28

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}

[#42229] Friday, September 26, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bradley

Total Points: 555
Total Questions: 102
Total Answers: 99

Location: Tajikistan
Member since Fri, Nov 27, 2020
4 Years ago
;