我有一个非常简单的JavaScript数组,可能包含重复项。
var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
我需要删除重复项并将唯一值放入一个新数组。
我可以指出我尝试过的所有代码,但我认为这没有用,因为它们不起作用。我接受jQuery解决方案。
我有一个非常简单的JavaScript数组,可能包含重复项。
var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
我需要删除重复项并将唯一值放入一个新数组。
我可以指出我尝试过的所有代码,但我认为这没有用,因为它们不起作用。我接受jQuery解决方案。
function removeDuplicates (array) {
var sorted = array.slice().sort()
var result = []
sorted.forEach((item, index) => {
if (sorted[index + 1] !== item) {
result.push(item)
}
})
return result
}
var srt_ = 0;
var pos_ = 0;
do {
var srt_ = 0;
for (var i in aLinks) {
pos_ = aLinks.indexOf(aLinks[i].valueOf(), 0);
if (pos_ < i) {
delete aLinks[i];
srt_++;
}
}
} while (srt_ != 0);
var uniqueCompnies = function(companyArray) {
var arrayUniqueCompnies = [],
found, x, y;
for (x = 0; x < companyArray.length; x++) {
found = undefined;
for (y = 0; y < arrayUniqueCompnies.length; y++) {
if (companyArray[x] === arrayUniqueCompnies[y]) {
found = true;
break;
}
}
if ( ! found) {
arrayUniqueCompnies.push(companyArray[x]);
}
}
return arrayUniqueCompnies;
}
var arr = [
"Adobe Systems Incorporated",
"IBX",
"IBX",
"BlackRock, Inc.",
"BlackRock, Inc.",
];
ES2015,1行代码,与map
很好地链接在一起,但仅适用于整数:
[1, 4, 1].sort().filter((current, next) => current !== next)
[1,1,2,2,3,3]
-> [1,2,3]
但是 [1,2,3,1,2,3]
-> [1,2,3,1,2,3]
。 - Kroltanfilter
的参数:它是 (value, index)
而不是 (current, next)
,所以对于 [1,4,1]
可行,但对于 [2,4,2]
就不行了... - Xenos["1", "4", "1"].sort().filter((value, index, array) => value !== array[index + 1])
- scipper
_.uniq(peoplenames)
解决了这个问题。请参考 http://lodash.com/docs#uniq 了解更多信息。 - Connor Leechconst result = data.sort().filter((v, idx, t) => idx==0 || v != t[idx-1]);
- Didier68