Anil Tomar
Anil Tomar

Reputation: 13

Query in finding unique array in javascript

I find script to get unique array in js. when i use if condition under filter function the return is not giving the correct result but when i simply return data the result is correct. Can anyone explain me why under if condition check result is wrong?

var x= ["apple","orange","banana","apple","mango"];
//var y= x.indexOf('apple');
//alert(y);

function checkdup(x)
{   
    let uniquearr= x.filter(function(val,index,arr){
    //return index== arr.indexOf(val); // return working correctly
    if(arr.indexOf(val)==index)
       {  return index; }   // showing wrong result why

    });
    //return uniquearr;
    console.log(uniquearr);
}

checkdup(x);

Upvotes: 1

Views: 54

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370679

The return value from filter is cast to true or false when deciding whether to keep an element in the returned array or not. When you're doing

return index== arr.indexOf(val);

you're returning a boolean - you're testing whether this element is the first occurrence of that element in the array. That's good, that's what you want. But when you

return index;

that is always true, except when index is 0 - which definitely isn't accomplishing what you want.

Upvotes: 1

Related Questions