JS - remove duplicates from array

Alex Lord
Alex Lord used Ask the Experts™
on
Im trying to delete dups in this array.

[2018, 2018, 2018]

Open in new window


array created from a for loop -

var years = [];

for(var i = 0; i < response.notes.length; i++){

        var d = new Date(parseInt(response.notes[i]['date'])*1000);
  
        var year = d.getFullYear();
   
        console.log("Year " + year);
          years.push(year);
        }
        

Open in new window





below code is my try at removing the dupes -

 years.push(year);
            sortedYears = years.slice().sort();
            for(var y = 0; y < sortedYears.length - 1; y++){
                if(sortedYears[y + 1] == sortedYears[y]){
                   unqYears.push(sortedYears[i]);
                   }
            }

Open in new window





simply what im trying to do is once the array is generated with years i want to go thought it and remove any years that are the same
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
ste5anSenior Developer

Commented:
hmm, I would use .filter(), something like:

unqYears= years.filter(function(item, position) {
    return years.indexOf(item) == position;
});

Open in new window

Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
You can filter your array:

var unqYears = years.filter( function(el, index, arr) { return index === arr.indexOf(el) } );

Open in new window

Commented:
            var years = ["2018", "2018", "2018"];
            var uniqueYears = [];
            $.each(years, function (i, el) {
                if ($.inArray(el, uniqueYears) === -1) uniqueYears.push(el);
            });

Open in new window

Commented:
3 solutions in 1 minute.

Author

Commented:
thx Everyone , solved the issue

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial