Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

javascript - Removing duplicate array values and then storing them [react]

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 would return...

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

(I'm using react jsx) Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do it in a one-liner

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

// it will return a collection of unique items

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!)

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;  
});

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...