Reputation: 845
function firstDuplicate(a) {
const duplicates = a.filter((el,idx) => {
let myVar = a.indexOf(el,idx+1);
console.log(myVar); // returns 4
if (myVar >= 0) return myVar; // duplicates becomes [1] instead of [4]
});
console.log('duplicates are',duplicates);
}
const myArr = [1,2,3,4,1];
I'm trying to return a value from filter instead of the array element. How do I do this? Ultimately I want to get all the duplicates in an array for a coding challenge.
Upvotes: 0
Views: 38
Reputation: 56473
The filter
method should be used to do what the name states, filter elements, i.e. retain elements that pass the provided predicate and discard those elements where the predicate returns false.
In this particular case, you're after the map
operation as you want to transform elements rather than filter.
Upvotes: 1