1

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.