我有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/