javascript - 搜索和过滤数组

标签 javascript arrays

假设我有一个这样的数组:

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/

相关文章:

javascript - python x[1 :2:3] in Javascript?

javascript - vuex getter中访问Nuxt插件功能

javascript - 通过匹配id映射2数组

javascript - 如果输入是复选框,则捕获正确输入的值

javascript - .data() 返回未定义

javascript - FB.login 无效的 redirect_uri (xd_proxy.php)

c++ - 指向(定义了指针数组)字符串的指针数组 : Are the strings stored sequential in memory?

javascript - 在 Javascript 中按值对哈希/数组进行排序

arrays - 在数组中组织多种类型的数据 swift 2

c# - 将值从动态文本框复制到锯齿状数组错误