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 } 
0

2 Answers 2

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) 
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.