kinda recursive solution i made for averages/mode in rosseta code challenges, the recursion exercises I did from w3resources (free) really helped! if your’e not so good with it check them out, there are also many on github, etc.
also what’s your’e opinion on this solution? pretty sure u can make it shorter

``````
function mode(arr) {
var filt = arr.filter((val, index) =>arr.indexOf(val) === index)
//if there are no duplicates in the array return arr
function checkArray (a, b) {
for (var i = 0; i < a.length; ++i) {
if (a[i] !== b[i]) return false;
}
return true;
}
if (checkArray(arr, filt)) {return arr}
//reduces every value in the array by 1 by indexOf, if it appears once it deletes it //(because indexOf matches the val) and if more than once
//it deletes the first duplicate (only thing that indexOf matches)
else {return mode(arr.filter((val, index) => arr.indexOf(val) !== index))};
}
console.log(mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]))

``````

User Agent is: `Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36`.

Challenge: Averages/Mode

I like the recursive approach, but I’d shorten the test for duplicates a bit:

``````function mode(arr) {
let filt = arr.filter((val, index) => arr.indexOf(val) === index);

//if there are no duplicates in the array return arr
if (filt.length === arr.length) {return arr}

//reduces every value in the array by 1 by indexOf, if it appears once it deletes it //(because indexOf matches the val) and if more than once
//it deletes the first duplicate (only thing that indexOf matches)
else {return mode(arr.filter((val, index) => arr.indexOf(val) !== index))};
}
console.log(mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]))
``````

You could shorten it further with a ternary and arrow syntax, but this is more of an example for “check out my fancy one-liner”.

``````const mode = arr => arr
.filter((val, index) => arr.indexOf(val) === index).length === arr.length ?
arr :
mode(arr.filter((val, index) => arr.indexOf(val) !== index))
``````
1 Like