Vanilla javascript for duplicates not working

lol @ the regex example. Obviously it would only work for sorted arrays with one digit numbers, but it is cool thinking outside of the box. I usually use Set in these cases, but in this case I think @jinisner would learn most from learning about .filter

2 Likes

@forkerino @0x0936 - i will have a look at them after i try myself , thanks

The array doesn’t need to be sorted, but you’re right that it only works for single digit numbers. I’ll call that scope creep - beyond the requirements of the project :slight_smile:

With sorted I meant that all the same numbers should be next to each other. It wouldn’t work with something like [1,2,1,2,1,2,3]

That’s true. Thanks for pointing that out - spoiler code fixed.

1 Like

@forkerino - hi i tried filter and it worked too, thanks …Though its a bit confusing as indexOf(currval) stores index of first instance while index of current value, this is a super shortcut, would have never understood any thing by this only …

var test = [3,3,3,3,3,1,1,1,5,7,7,7,6,3,3,3,3,3,3,3,7,3,9,23,12,12,12,12,12];

var res = test.filter(function(currval,index,arr){
    return  arr.indexOf(currval) === index;
});

console.log(res);

This code will seem simple soon enough. Congrats on making it work with filter. I can understand why you’d say that it is hard to grasp at first, but if you know that the return value of .indexOf() is the first occurrence of a value in an array, it reads quite well in my opinion. At least better than nested for loops where the code itself says very little about what it is supposed to be doing (in which case naming your variables and functions properly is very important and often comments are necessary as well). With .filter any reasonably experienced developer will understand what is going on there as the name says it all.

Here is a very simple solution using set:

var test = [3,3,3,1,1,1,5]; 
var noDuplicates = Array.from(new Set(test));

EDIT: I just saw 0x0936 already posted this.

@dcenatiempo - Yes , unfortunately i have not yet reached Set and so i do not understand it, thanks for your feed back …

Well there is no better time to learn it than now! I only learned about it last week!
It’s pretty simple, actually, set is very similar to array, except there are only allowed 1 unique occurance of each item.
So basically, my code takes an array with duplicates, turns it into a set (removing duplicates) and then turns it back into an array.