× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

How to remove duplicates within a Javascript array using ES6 in just one line

May 31, 2016
<p> We work on arrays all the time and one of the most frequent operations that we perform on arrays is removing duplicates. There are a few ways to do this. </p> <ol> <li>Loop over an array, and move every item into a new array if it does not already exist in the new array.</li> <li>Use the filter function to do the same activity.</li> </ol> <p>A newer, concise and simpler way is to use the new Set data strucuture. </p> <blockquote> <p>Use the <strong>Set</strong> data structure, which automatically takes an iterable and removes duplicates. Then, use the <strong>from </strong>function of the Array object which will then take an iterable and convert it into an array. </p> </blockquote> <p><span style="color:rgb(95, 99, 102)">Check out the snippet below :</span></p> <pre><code>let fruits = ['apple','banana','orange','apple','mango','banana']; let fruits_without_duplicates = Array.from(new Set(fruits)); console.log(fruits_without_duplicates); //["apple", "banana", "orange", "mango"]</code></pre> <p> </p> <p>Happy coding!</p>
comments powered by Disqus