Javascript Data Type How to - Delete duplicate elements from an array








Question

We would like to know how to delete duplicate elements from an array.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!-- w w  w . j  a v  a  2s .c  om-->
var arr = [1,2,2,3,4,5,5,5,6,7,7,8,9,10,10];
function squash(arr){
    var tmp = [];
    for(var i = 0; i < arr.length; i++){
        if(tmp.indexOf(arr[i]) == -1){
           tmp.push(arr[i]);
        }
    }
    return tmp;
}
document.writeln(squash(arr));

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: