+ 1

can someone explain me this

function array_element_mode(arr) { var ctr = [], ans = 0; for(var i = 0; i < 10; i++) { ctr.push(0); } for(var i = 0; i < arr.length; i++) { ctr[arr[i] - 1]++; if(ctr[arr[i] - 1] > ctr[ans]) { ans = arr[i] - 1; } } return ans + 1; } console.log(array_element_mode([1, 2, 3, 2, 2, 8, 1, 9]))

9th Oct 2020, 5:40 AM
Ali Zain
Ali Zain - avatar
4 Answers
+ 2
The function returns the most repeating number in arr. In my opinion the code is bad and shouldn't be taken as example when learning. Do you have a doubt with a particular line/block of the code or you want to hear the full explanation.
9th Oct 2020, 6:52 AM
Kevin ★
+ 2
Thanks for your understanding. In this article you can see the same algorithm used to find the most common string: https://medium.com/@AmJustSam/how-to-find-most-frequent-item-of-an-array-12015df68c65 There's a section called: "If code above is complicated for some of you then let me explain it.". Try to find it for a better explanation.
9th Oct 2020, 7:11 PM
Kevin ★
+ 1
Thanks Kevin ★ Btw can you share any sources where I can get codes like this in a more simpler way
9th Oct 2020, 7:07 AM
Ali Zain
Ali Zain - avatar
+ 1
Thank you @kevin :)
10th Oct 2020, 9:48 AM
Ali Zain
Ali Zain - avatar