假设我有一个这样的数组:
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, my' 可以在紧接着的下一个元素 'hello, my name is' 中找到,所以 'hello, my' 应该被删除。
我要过滤的实际数组是:
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]);
}
}
最佳答案
我猜你想
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);
关于javascript - 搜索和过滤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38389073/