NodeJS:如何从Array中删除重复项

Yo *_*ngh 24 arrays duplicates node.js

我有一个数组:

[
    1029,
    1008,
    1040,
    1019,
    1030,
    1009,
    1041,
    1020,
    1031,
    1010,
    1042,
    1021,
    1030,
    1008,
    1045,
    1019,
    1032,
    1009,
    1049,
    1022,
    1031,
    1010,
    1042,
    1021,
]
Run Code Online (Sandbox Code Playgroud)

现在我想从中删除所有重复项.NodeJ中是否有任何方法可以直接执行此操作.

mih*_*hai 61

不,node.js中没有内置方法,但是有很多方法可以在javascript中执行此操作.所有你需要做的就是环顾四周,因为这已经得到了解答.

uniqueArray = myArray.filter(function(elem, pos) {
    return myArray.indexOf(elem) == pos;
})
Run Code Online (Sandbox Code Playgroud)

  • 较短版本:`uniques = array.filter((x, i) => i === array.indexOf(x))` (3认同)

Ris*_*vik 30

没有内置方法可以从数组唯一方法中获取,但是您可以查看名为lodash的库,它具有如此出色的方法_.uniq(array).

此外,提出替代方法,因为Node.js现在支持Set.而不是使用第三方模块使用内置替代品.

var array = [
    1029,
    1008,
    1040,
    1019,
    1030,
    1009,
    1041,
    1020,
    1031,
    1010,
    1042,
    1021,
    1030,
    1008,
    1045,
    1019,
    1032,
    1009,
    1049,
    1022,
    1031,
    1010,
    1042,
    1021,
];

var uSet = new Set(array);
console.log([...uSet]); // Back to array
Run Code Online (Sandbox Code Playgroud)

  • 不应该是 [`_.uniq`](https://lodash.com/docs#uniq) 而不是 `_.unique` 吗? (3认同)
  • 确实,该方法称为`_.uniq`,已修复。 (3认同)
  • 确切地说 - 作为 2022 年的单行:`Array.from(new Set(array))` (3认同)