0

I want a distinct array. I couldn't figure it out how it works

---This is my Function---

var Array = [2, 0, 1, 9, 1, 3, 2, 4, 5, 5, 3, 4]

function distinctArray(val){
    var newArray=[];
    for(var i=0 ; i < val.length; i++){
        if (newArray.indexOf(val[i]) > -1){
            newArray.push(val[i])
        }
    }
    return newArray
}
iharsimran30
  • 21
  • 1
  • 3

2 Answers2

1

You probably meant to type

if (newArray.indexOf(val[i]) == -1) // if it does NOT already exist

instead of

if (newArray.indexOf(val[i]) > -1)
guysigner
  • 2,822
  • 1
  • 19
  • 23
0

You could just use Array.filter() for keeping only element which are unique

var array = [2, 0, 1, 9, 1, 3, 2, 4, 5, 5, 3, 4];
var distinct = array.filter((x,i,arr) => arr.lastIndexOf(x) === i);
console.log(distinct);
kevin ternet
  • 4,514
  • 2
  • 19
  • 27