将数组与排序数组进行比较,选择第一个元素

Compare array with sorted Array, pick first element

设置如下:

targets = ['green','orange','red'];  //targets are in order of priority
sources = ['redalert','blackadder','greenlantern'];

我正在尝试创建一个 returns 包含最高优先级目标字符串的源元素的函数。在这种情况下,它将是 'greenlantern',因为它包含字符串 'green',它比 'redalert'.

中的 'red' 具有更高的优先级

我已经使用 for 循环和临时数组完成了它,但我知道这些操作不是我的强项,而且我现实生活中的数组要大得多,所以我想优化执行。我也尝试过使用 Lodash,但不知道如何一步完成。可能吗?

在我看来,它必须:

但我相信还有更好的方法。

保持简单:

var sortedSources = _.sortBy(sources, function(source){
  var rank = 0
  while(rank < targets.length){
    if(source.indexOf(targets[rank]) > -1){
      break
    }else{
      rank++
    }
  }
  return rank
})

来源现在按目标优先级排序,因此 sortedSources[0] 是你的人选。

这是另一种使用 reduce() instead of sortBy() 的 lodash 方法:

_.reduce(targets, function(result, target) {
    return result.concat(_.filter(sources, function(source) {
        return _.includes(source, target);
    }));
}, []);

由于 targets 已经有序,您可以对其进行迭代并以相同的顺序构建结果。您使用 reduce() 是因为您正在迭代构建结果,这不是直接映射。

在 reduce 回调中,您可以通过使用 filter() and includes() 找到合适的 sources.

结果 concat()

这为您提供了 排序数组 ,但如果您只想要对应于第一个 [=18] 的第一个 source,它也会做很多不必要的工作=]:

_.find(sources, _.ary(_.partialRight(_.includes, _.first(targets)), 1));

或者,如果您不想编写回调函数:

_.find(sources, function(item) {
    return _.includes(item, _.first(targets));
});

本质上,find() will only iterate over the sources collection till there's a match. The first() 函数让您第一个 target 寻找。