如何从.filter而不是元素返回一个值(How to return a value from .filter instead of the element)
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];我试图从过滤器而不是数组元素返回一个值。 我该怎么做呢? 最终我想获得数组中所有重复的代码以应对编码挑战。
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.
最满意答案
应该使用filter方法来完成名称所指定的过滤元素 ,即保留传递提供的谓词的元素,并放弃谓词返回false的元素。
在这种特殊情况下,您正在执行map操作,因为您想要转换元素而不是过滤器 。
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.
更多推荐
发布评论