NodeJS:如何从数组中删除重复项[重复]

时间:2021-11-26 21:48:38

This question already has an answer here:

这个问题在这里已有答案:

I have an 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,
]

Now I want to remove all the duplicates from it. Is there any method in NodeJs which can directly do this.

现在我想从中删除所有重复项。 NodeJ中有没有可以直接执行此操作的方法。

2 个解决方案

#1


41  

No, there is no built in method in node.js, however there are plenty of ways to do this in javascript. All you have to do is look around, as this has already been answered.

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

uniqueArray = myArray.filter(function(elem, pos) {
    return myArray.indexOf(elem) == pos;
})

#2


17  

No there is no built in method to get from array unique methods, but you could look at library called lodash which has such great methods _.uniq(array).

没有内置的方法可以从数组唯一方法中获取,但你可以看一下名为lodash的库,它有很好的方法_.uniq(array)。

Also, propose alternative method as the Node.js has now support for Set's. Instead of using 3rd party module use a built-in alternative.

此外,提出替代方法,因为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

#1


41  

No, there is no built in method in node.js, however there are plenty of ways to do this in javascript. All you have to do is look around, as this has already been answered.

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

uniqueArray = myArray.filter(function(elem, pos) {
    return myArray.indexOf(elem) == pos;
})

#2


17  

No there is no built in method to get from array unique methods, but you could look at library called lodash which has such great methods _.uniq(array).

没有内置的方法可以从数组唯一方法中获取,但你可以看一下名为lodash的库,它有很好的方法_.uniq(array)。

Also, propose alternative method as the Node.js has now support for Set's. Instead of using 3rd party module use a built-in alternative.

此外,提出替代方法,因为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