Javascript Set filter array to keep only unique

Introduction

Write a function uniq() that takes in an array arr then returns unique items of arr.

For example

uniq(['a', 'b', 'a']) === ['a', 'b']


/*/*  w  w w  .j  a v  a2 s  . c o  m*/
 function uniq(arr) {
   return arr.filter(function(currentValue, index) {
     if(arr.indexOf(currentValue) === index) {
       return true;
     } else {
       return false;
     }
   });
 }
 */

function uniq(arr) {
   return Array.from(new Set(arr));
}
console.log(uniq(['a', 'b', 'a']));



PreviousNext

Related