Practical guides, tutorials, and insights from years of building web and desktop applications. Check out code examples you can actually use!
Use Filter to Eliminate Duplicates in Javascript Array
Use array filters to remove duplicates in an array. We have seen how we could use sets or an intermediate object in a loop to eliminate duplicates within array.There always is a better way of doing things. Why not use filter to make the code more readable and not use set at the same time :) ? Consider this array - const nums = [1, 5, 0, 1, 2, 3]; The below code will create a unique array. const uniqueNums = nums.filter((num, index) => { return nums.indexOf(num) == index; }); console.log(uniqueNums); // [ 1, 5, 0, 2, 3 ] Why will this work? Well, because nums.indexOf(num) always returns the first index of a particular element. ...