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

Coding for Kids

What is coding? In coding we build a program to do a specific task for us. Code: A code is a set of computer instructions and when you will ...