假设我有这样一个数组:
var arr = ['hello, my', 'hello, my name is', 'hello, my name is newton', 'hello, his', 'hello, his name is', 'hello, his name is pluto', 'hello, she is britney'];我想把它过滤到:
var arr = ['hello, my name is newton', 'hello, his name is pluto', 'hello, she is britney'];我不知道如何放置,但条件是,如果可以在其他元素上找到数组元素的字符串,则应该删除它。就像'hello,我的‘完全可以在下面的元素'hello,我的名字’so 'hello,我的“应该删除。
我要筛选的实际数组是:
var arr = ['11 22 13', '11 22 13 34', '11 22 13 34 15', '11 22 13 34 35', '11 22 23', '11 22 23 34', '11 22 23 34 15', '11 22 23 34 35', '31 22 13', '31 22 13 34', '31 22 13 34 15', '31 22 13 34 35', '31 22 23', '31 22 23 34', '31 22 23 34 15', '31 22 23 34 35'];我试着把它分成不同的组,但我仍然不知道该如何处理它。不管怎样,我会展示给你看的:
var threelink = [];
var fourlink = [];
var fivelink = [];
for(var i=0; i < arr.length; i++){
if(arr[i].length>8&&arr[i].length<12){
fourlink.push(arr[i]);
}
else if(arr[i].length>11){
fivelink.push(arr[i]);
}
else {
threelink.push(arr[i]);
}
}发布于 2016-07-15 07:04:57
普通的旧嵌套循环解决方案,可能比这个线程中的变化更快,因为内部循环查看数组的收缩部分:
function uniqueContents(arr) {
var work = arr.slice(), result = [],
i, j, l = arr.length, found;
work.sort(function (a, b) {
return a.length > b.length;
});
for (i = 0; i < l; i++) {
if (!work[i]) break;
found = false;
for (j = i + 1; j < l; j++) {
if (!work[j]) break;
found = work[j].indexOf(work[i]) > -1;
if (found) break;
}
if (!found) result.push(work[i]);
}
return result;
}除此之外,这是副作用免费(不扭曲输入)和容忍空/未定义的值。
发布于 2016-07-15 06:26:14
我想你想
arr.filter(function(e, i, a) {
return !a.some(function(e2) {
return e2 !== e && e2.includes(e);
});
})这意味着要过滤数组,只保留没有(!some)其他包含它的元素(但不等于它)的元素。
它与ES6箭头函数比较紧凑:
arr.filter((e, i, a) => !a.some(e2 => e2 !== e && e2.includes(e)));
var arr = ['hello, my', 'hello, my name is', 'hello, my name is newton', 'hello, his', 'hello, his name is', 'hello, his name is pluto', 'hello, she is britney'];
var filtered = arr.filter((e, i, a) => !a.some(e2 => e2 !== e && e2.includes(e)));
console.log(filtered);
发布于 2016-07-15 06:51:48
您可以使用Array#reduce和Array#filter来检查结果集中的字符串是否要过滤掉,以及实际值是否要插入结果集中。
这适用于未排序的数据。
var arr = ['hello, my', 'hello, my name is', 'hello, my name is newton', 'hello, his', 'hello, his name is', 'hello, his name is pluto', 'hello, she is britney', 'abc', 'ab'],
result = arr.reduce(function (r, a, i) {
var push = true;
r = r.filter(function (b) {
push = push && b.indexOf(a) === -1;
return a.indexOf(b) === -1;
});
push && r.push(a);
return r;
}, []);
console.log(result);
https://stackoverflow.com/questions/38389073
复制相似问题