我有一个数组如:
var aos = ["a","a","b","c","d"];
我想知道我是否可以找到每个索引的副本并将它们存储到诸如arraylist之类的东西中?例如,我们从:
开始 aos[0]
然后检查是否
a
,它将继续在数组中运行,将索引0中具有该值的所有元素存储到列表(例如arraylist或集合)中,然后从列表中删除它们。这可能吗?
答案 0 :(得分:2)
var uniq =_.uniq(aos)
或长途跋涉(ES5):
var uniq = aos.reduce(aos, function(memo, val) {
if (!aos.some(function(elem) { return elem === val; })) {
return memo.push(val);
}
}, []);
如果你想支持ES3,那么:
var uniq = [];
for (var i = 0, ii = aos.length; i < ii; i++) {
var contains = false;
for (var j = 0, jj < uniq.length; j < jj; j++) {
if (uniq[j] === aos[i]) {
contains = true;
break;
}
}
if (!contains) {
uniq.push(aos[i]);
}
}
将重复项存储在新数组中:
var duplicates = _.select(aos, function(val) {
var true = _.after(2, function() { return true; });
return _.any(aos, function(elem) {
return elem === val ? true() : false;
});
});
_.uniq
,Array.prototype.reduce
,Array.prototype.some
,_.any
,_.select
,_.after
答案 1 :(得分:0)
基本上你想删除重复的项目?,试试这个:
function unique_array(array) {
var result = []
for (var i = 0; i < array.length; ++i) {
for (var j = i + 1; j < array.length; ++j) {
if (array[i] === array[j]) {
j = ++i;
}
}
result.push(array[i]);
}
return result;
}
或者
Array.prototype.unique = function() {
var result = []
for (var i = 0; i < this.length; ++i) {
for (var j = i + 1; j < this.length; ++j) {
if (this[i] === this[j]) {
j = ++i;
}
}
result.push(this[i]);
}
return result;
}
Array.prototype.duplicates = function() {
var result = []
for (var i = 0; i < this.length; ++i) {
for (var j = i + 1; j < this.length; ++j) {
if (this[i] === this[j]) {
result.push(this[i]);
j = ++i;
}
}
}
return result;
}
// aos.unique() => a,b,c,d
// aos.duplicates() => a