javascript - 某个单词出现在字符串末尾

标签 javascript underscore.js

我有2个数组

array1 = ["e4dfda158c82cc931e2479e32bde42defacebook", "5824fb40c4a97e21ef9715ea69c1cfb9twitter", "6da098061f82c215f37a4949b1555e26linkedinpage"];

array2 = ["facebook", "twitter", "linkedin", "xing", "weibo", "instagram", "googleplus", "pinterest"];

我想比较这两个数组并获得如下所示的输出

output = ["facebook", "twitter"]

比较基于检查 array1 中“array2”中每个元素是否存在(即在字符串末尾)。 我已经尝试使用多个 for 循环,但对我不起作用,有没有更好的方法使用 Underscore.js、lodash。

已尝试

array2.forEach(function(data) {
    array1.forEach(function(data2) {
         n = data2.indexOf(data);
         if(n!=-1) {
            console.log(data)
        }
    })
})

最佳答案

过滤 array2 来查找满足 array1 中存在某个以该单词结尾的元素的条件的单词:

array2 . filter(word => 
    array1 . some(string => 
        string.endsWith(word)
    )
)

您可以使用下划线或 lodash 等效项,但实际上没有理由这样做,除非您有浏览器支持问题(例如 IE)。

关于javascript - 某个单词出现在字符串末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35810294/

相关文章:

javascript - 使用 jQuery 更改 HTML 属性

javascript - 数据 URI 替代方案

javascript - 下划线嵌套对象元素的groupBy

javascript - 如何在 Visual Studio Code 中使用下划线而不首先使用 "activating"?

javascript - 使用 Underscore.js 从数组中删除项目

javascript - 当计时器结束时replaceWith

javascript - 如何将excelsheet行高设置为自动,以便内容可以使用exceljs在单元格中自动调整

javascript - 从复选框附加字符串单击

javascript - 对象文字和原型(prototype)继承?

javascript - JSON 中的嵌套键/值结构