设置如下:
targets = ['green','orange','red']; //targets are in order of priority
sources = ['redalert','blackadder','greenlantern'];
我正在尝试创建一个函数,该函数返回包含最高优先级目标字符串的一个源元素。在这种情况下,它将是“greenlantern”,因为它包含字符串“green”,其优先级高于“redalert”中的“red”。
我已经使用 for 循环和临时数组完成了它,但我知道这些操作不是我的强项,而且我现实生活中的数组要大得多,所以我想优化执行。我也尝试过使用 Lodash,但不知道如何一步完成。可能吗?
在我看来,它必须:
对于每个目标,循环遍历源,如果源元素与目标元素匹配,则中断并返回。
但我确信有更好的方法。
最佳答案
这是另一种使用 reduce() 的 lodash 方法而不是 sortBy() :
_.reduce(targets, function(result, target) {
return result.concat(_.filter(sources, function(source) {
return _.includes(source, target);
}));
}, []);
由于 targets
已经有序,您可以对其进行迭代并以相同的顺序构建结果。您使用 reduce()
是因为您正在迭代构建结果,这不是直接映射。
在 reduce 回调中,您可以使用 filter() 来 concat()
结果和 includes()找到合适的来源
。
这为您提供了排序数组,但如果您只想要与第一个目标<相对应的第一个
:
source
,它也会做很多不必要的工作
_.find(sources, _.ary(_.partialRight(_.includes, _.first(targets)), 1));
或者,如果您不想编写回调函数:
_.find(sources, function(item) {
return _.includes(item, _.first(targets));
});
本质上,find()只会遍历 sources
集合直到找到匹配项。 first()函数为您提供要查找的第一个 target
。
关于arrays - 将数组与排序数组进行比较,选择第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31195169/