Remove duplicates from an array? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Remove duplicates from an array?

var arr = [1,2,3,4,3,5]; how could I remove duplicates on any given array?

26th Sep 2017, 12:58 AM
djorborn
djorborn - avatar
3 Answers
+ 13
var arr = [1, 2, 3, 4, 3, 5]; var new_arr = []; for (var i = 0; i < arr.length; i++) { var flag = 0; for (var j = 0; j < new_arr.length; j++) { if (arr[i] === new_arr[j]) flag = 1; } if (flag === 0) new_arr.push(arr[i]); } alert(new_arr);
26th Sep 2017, 1:12 AM
Krishna Teja Yeluripati
Krishna Teja Yeluripati - avatar
+ 3
var arr = [1,2,3,4,3,5]; Array.prototype.uni = function(){ return this.filter((v,i,a)=>a.indexOf(v,i+1)===-1?true:false); } alert(arr.uni()); https://code.sololearn.com/WBA29niGTZsj/?ref=app
26th Sep 2017, 1:31 AM
Calviղ
Calviղ - avatar
+ 2
Loop thru the list adding each number to another new list but first checking if that number is in the new list. If the number is already in the new list you have a duplicate. Then just remove it.
26th Sep 2017, 1:05 AM
Arthur Tripp
Arthur Tripp - avatar