JavaScript method to return an array with all unique elements

Took 11 minutes and 20 seconds to code JavaScript method to return an array with all unique elements. Here is the code snippet.

Code:

arr = [1,2,3,4,4,3,2,1,"1","2","3","4"];
function uniqueArray(arr) {
arr2 = [];
for (var i = 0; i < arr.length; i++) {
for (var y = i + 1; y < arr.length; y++) {
if (arr[i] == arr[y]) {
delete arr[y];
}
}
}
for (var z = 0; z < arr.length; z++) {
if (arr[z] != undefined) {
arr2.push(arr[z]);
}
}
return arr2;
}

document.write(uniqueArray(arr));

Result:

1,2,3,4

No comments:

Post a Comment

GITEX Dubai Talk by Saion Gupta and Saiasmi Gupta

Good morning, everyone. I'm Saion Gupta, the Founder of 10xCoderKids and the Guinness World Record holder for the youngest computer prog...