字符串末尾的单词出现 - underscore.js

Occurrence of of a word at the end of string - underscore.js

我有 2 个数组

array1 = ["e4dfda158c82cc931e2479e32bde42defacebook", "5824fb40c4a97e21ef9715ea69c1cfb9twitter", "6da098061f82c215f37a4949b1555e26linkedinpage"]
array2 = ["facebook", "twitter", "linkedin", "xing", "weibo", "instagram", "googleplus", "pinterest"]

我想比较这两个数组并像下面这样输出

output = ["facebook", "twitter", "linkedin"]

尝试并工作 - 我需要一种 underscore.js 方法来做同样的事情

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

使用的方法:chain, map, find.value() 是链的一部分。

var output = _.chain(array1).map(function (el1) {
  return _.find(array2, function (el2) {
    return el1.indexOf(el2) > 1;
  });
}).compact().value();

JS Bin demo

由于对数组进行了多项操作,链方法仅用于查找,您始终可以通过将第一个操作的结果数组分配给一个值然后将该数组发送到适当的下一个操作来执行下一个操作函数调用作为参数。

地图:

Produces a new array of values by mapping each value in list through a transformation function (iteratee). The iteratee is passed three arguments: the value, then the index (or key) of the iteration, and finally a reference to the entire list.

映射return一个新数组,其长度与发送到其中的旧数组相同。它迭代旧数组的每个值并将新值推送到由转换函数return编辑的新值。

查找:

Looks through each value in the list, returning the first one that passes a truth test (predicate), or undefined if no value passes the test.

真假判断由你传入的"predicate"回调函数的return值决定。

使用 find 迭代值的好处是,一旦 underscore 找到匹配项,它就会知道停止迭代数组并节省宝贵的计算时间。

紧凑型:

Returns a copy of the array with all falsy values removed. In JavaScript, false, null, 0, "", undefined and NaN are all falsy.

Compact 改变数组的长度。这可能不是你想要做的,特别是如果你依赖于你的结果数组与源数组相同。 Compact 会过滤掉所有未定义的数据。

如果您不打算使用 compact,则根本不需要链,您的代码只需像这样使用地图:

var output = _.map(array1, function (el1) {
  return _.find(array2, function (el2) {
    return el1.indexOf(el2) > 1;
  });
});