比较数组和排序数组,选择第一个元素

时间:2015-07-02 21:45:11

标签: arrays lodash

设置如下:

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

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

我已经使用了for循环和临时数组,但我知道这些操作不是我的强项,而且我的现实生活数组更大,所以我想优化执行。我也尝试过Lodash,但无法一步到位地弄清楚如何做到这一切。有可能吗?

我看到它的方式,它必须:

  • for each target, loop through sources, if source elem matches target elem, break and return.

但我确信有更好的方法。

2 个答案:

答案 0 :(得分:1)

保持简单:

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]是你的人。

答案 1 :(得分:1)

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

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

由于targets已经按顺序排列,您可以迭代它并以相同的顺序构建结果。您使用reduce()是因为您正在迭代地构建结果,而不是直接映射。

在reduce回调中,您可以使用filter()includes()concat()找到合适的sources。{/ p>

这会为您提供排序数组,但如果您只想要与第一个source对应的第一个target,它也会做很多不必要的工作}:

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

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

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

基本上,find()只会迭代sources集合,直到匹配为止。 first()函数会为您提供第一个要查找的target