我正在尝试从当前数组中删除重复的数组值。而且我想将新列表(没有重复的列表)存储到一个新变量中。
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 });
如何删除重复的名称并将非重复的名称放入新变量中?
即:uniqueNames将返回…
["Daniel","Lucas","Gwen","Henry","Jasper"]
(我正在使用react jsx)谢谢!
您可以单线完成
const uniqueNames = Array.from(new Set(names));
//它将返回唯一项的集合
请注意,@ Wild Widow指出了您的错误之一-您未使用return语句。(当我们忘记时,它很烂,但是发生了!)
我还要补充一点,如果考虑到filter(a,b,c)函数的第三个参数- 其中c是要遍历的数组,则可以简化代码,并且回调可以更重用。这样,您可以按照以下方式重构代码:
const uniqueNames = names.filter((val, id, array) => { return array.indexOf(val) == id; });
此外,如果使用es6,甚至不需要return语句
const uniqueNames = names.filter((val,id,array) => array.indexOf(val) == id);