删除重复的数组值然后存储它们 [react]

IT技术 javascript reactjs
2021-04-23 02:11:54

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

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

5个回答

你可以用单线完成

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

你忘了returnfilter通话中使用语句

const namesArr = duplicatesArray.filter(function(elem, pos) {
    return duplicatesArray.indexOf(elem) == pos;
}); 

如果要删除包含相同“id”的重复值,您可以使用它。

const arr = [
  { id: 2, name: "sumit" },
  { id: 1, name: "amit" },
  { id: 3, name: "rahul" },
  { id: 4, name: "jay" },
  { id: 2, name: "ra one" },
  { id: 3, name: "alex" },
  { id: 1, name: "devid" },
  { id: 7, name: "sam" },
  ];

function getUnique(arr, index) {

  const unique = arr
       .map(e => e[index])

       // store the keys of the unique objects
       .map((e, i, final) => final.indexOf(e) === i && i)

       // eliminate the dead keys & store unique objects
      .filter(e => arr[e]).map(e => arr[e]);      

   return unique;
}

console.log(getUnique(arr,'id'))

结果 :

> Array 
[ 
  { id: 2, name: "sumit" },
  { id: 1, name: "amit" },
  { id: 3, name: "rahul" },  
  { id: 4, name: "jay" },  
  { id: 7, name: "sam" }
]
由于我发现此代码非常混乱,因此我将重构后的版本作为单独的答案发布。
2021-06-02 02:11:54

由于我发现在某处使用了@Infaz 的答案的代码并且让我非常困惑,所以我想我会分享重构的功能。

function getUnique(array, key) {
  if (typeof key !== 'function') {
    const property = key;
    key = function(item) { return item[property]; };
  }
  return Array.from(array.reduce(function(map, item) {
    const k = key(item);
    if (!map.has(k)) map.set(k, item);
    return map;
  }, new Map()).values());
}

// Example
const items = [
  { id: 2, name: "sumit" },
  { id: 1, name: "amit" },
  { id: 3, name: "rahul" },
  { id: 4, name: "jay" },
  { id: 2, name: "ra one" },
  { id: 3, name: "alex" },
  { id: 1, name: "devid" },
  { id: 7, name: "sam" },
];
console.log(getUnique(items, 'id'));
/*Output:
[ 
  { id: 2, name: "sumit" },
  { id: 1, name: "amit" },
  { id: 3, name: "rahul" },  
  { id: 4, name: "jay" },  
  { id: 7, name: "sam" }
]
*/

最后,一个答案奏效了。谢谢。
2021-06-17 02:11:54

你也可以这样做

{Array.from(new Set(yourArray.map((j) => j.location))).map((location) => (
          <option value={`${location}`}>{location}</option>
        ))}