Removing duplicate array values and then storing them [react]

前端 未结 5 626
Happy的楠姐
Happy的楠姐 2021-02-06 16:49

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          


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-06 17:08

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

提交回复
热议问题