如何从.filter而不是元素返回一个值(How to return a value from .filter instead of the element)

编程入门 行业动态 更新时间:2024-10-27 12:27:33
如何从.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.

更多推荐

本文发布于:2023-07-26 17:44:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1278860.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:而不是   元素   filter   return   element

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!