NodeJS:如何从数组中删除重复项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23237704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NodeJS: How to remove duplicates from Array
提问by Yo Yo Saty Singh
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.
现在我想从中删除所有重复项。NodeJs中是否有任何方法可以直接做到这一点。
回答by mihai
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;
})
回答by Risto Novik
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 了。而不是使用 3rd 方模块使用内置的替代品。
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

