删除重复的数组值,然后将其存储[反应] [英] Removing duplicate array values and then storing them [react]

查看:43
本文介绍了删除重复的数组值,然后将其存储[反应]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从当前数组中剥离重复的数组值.我想将新列表(没有重复的列表)存储到一个新变量中.

I'm trying to strip the duplicate array values from my current array. And I'd like to store the fresh list (list without duplicates) into a new variable.

var names = ["Daniel","Lucas","Gwen","Henry","Jasper","Lucas","Daniel"];

const uniqueNames = [];
const namesArr = names.filter((val, id) => {
    names.indexOf(val) == id;  // this just returns true
});

如何删除重复的名称并将非重复的名称放入新变量中?

How can I remove the duplicated names and place the non-duplicates into a new variable?

ie:uniqueNames将返回...

ie: uniqueNames would return...

["Daniel","Lucas","Gwen","Henry","Jasper"] 

(我正在使用React jsx)谢谢!

(I'm using react jsx) Thank you!

推荐答案

您可以单线完成

const uniqueNames = Array.from(new Set(names));

//它将返回唯一项的集合

// it will return a collection of unique items

请注意,@ Wild Widow指出了您的一个错误-您未使用return语句.(当我们忘记时,它很烂,但是确实发生了!)

Note that @Wild Widow pointed out one of your mistake - you did not use the return statement. (it sucks when we forget, but it happens!)

我还要补充一点,如果考虑到filter(a,b,c)函数的第三个参数-其中c是要遍历的数组,则可以简化代码,并且回调可以更重用.话虽如此,您可以按照以下方式重构代码:

I will add to that that you code could be simplified and the callback could be more reusable if you take into account the third argument of the filter(a,b,c) function - where c is the array being traversed. With that said you could refactor your code as follow:

const uniqueNames = names.filter((val, id, array) => {
   return array.indexOf(val) == id;  
});

此外,如果您使用es6,甚至不需要return语句

Also, you won't even need a return statement if you use es6

const uniqueNames = names.filter((val,id,array) => array.indexOf(val) == id);

这篇关于删除重复的数组值,然后将其存储[反应]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆