## DEV Community

Karan

Posted on • Updated on

# Clean code and why I'm behind!

Hello everyone,

This is my first post here, so I'll try & keep it shortπ. I've recently started sharpening my javascript axe on Codewars after several days working on Watch & Code by Gordon Zhu, which is amazing first step to get started with JS since I knew nothing, still don't know much, anyway to the point...

There's kata on codewars, an easier one for the experts, but this one is at 6 kyu and it goes like this:

###### Given a list lst and a number N, create a new list that contains each number of lst at most N times without reordering. For example if N = 2, and the input is [1,2,3,1,2,1,2,3], you take [1,2,3,1,2], drop the next [1,2] since this would lead to 1 and 2 being in the result 3 times, and then take 3, which leads to [1,2,3,1,2,3].

So essentially, you need to remove the Nth occurance of a digit without spoiling the indexes.

Easy right? I know now! Not last week when I nearly spent 3 days (please don't judge me) breaking my head when I should've just thought about it clearly and read the filter function documentation clearly.

Now for the depressingly bad code I wrote, in retrospect I am ashamed!π

``````function deleteNth(arr, n){
var final = [];
var last = [];
var k = [];
var f = [];
var count_inside = 0;

arr.forEach(function(item, index){
if(last.indexOf(item)===-1){
final[index] = arr.map(i=>{
if(i===item && count_inside<n){
count_inside +=1;
return item;
}
else{
return '';
}
}
);
count_inside = 0;
last.push(item);
}
});

k = final.filter(function(i){return true;})

for(var i =0;i<arr.length;i++){
var sum = '';
for(var j = 0;j<k.length;j++){
sum += k[j][i];
}
f.push(parseInt(sum));
}
return f.filter(function(p){return p>=p});
}
``````

I'm essentially trying to do the following:

1. Filter the array with a number, and get the result in an array with that number and all other indexes as empty or ''.
2. Do this other numbers without repeating the number from step 1.
3. Compress the resulting arrays into a single one and BOOM SERVE!

While still proud submitting it...knowing fully well that someone might have done it in a single LINE! And yeah after submission...I see this:

``````function deleteNth(arr,x) {
var result = [];
return arr.filter(function(n) {
result[n] = (result[n]||0) + 1;
return result[n] <= x;
});
}
``````

That's all it took!

##### Just count the times a number appeared and if it appeared more than N times, don't put it in the returned array.

And I missed that! I understand it will take me somewhile to think that clearly.
But I just wanted to put this out and maybe it might help you think in a different way today :).

Thank you Codewars!