JavaScript函数可找到数组中的第一个结果

时间:2019-01-11 00:12:04

标签: javascript

我正在寻找一种实用的方法来找到数组中的第一个结果。

let result;
for (let i = 0; i < array.length; i++) {
  result = functionThatCalulatesResult(array[i]);
  if (result) {
    break;
  }
}

这是当务之急。

const item = array.find(i => functionThatCalulatesResult(i));

但是现在我必须再次计算结果。

const result = array.reduce(
  (result, item) => result ? result : functionThatCalulatesResult(i), 
  undefined
);

但是reduce会遍历所有不需要迭代的项目。

我正在寻找类似的东西

const result = firstResult(array, i => functionThatCalulatesResult(i));

这将返回该函数的第一个真实结果,而不会迭代经过第一个结果的项目。

我能想到的最有效的方法是

const firstResult = (array, func) => {
  let result;
  array.some(i => result = func(i));
  return result;
}

但是它并不能完全改变结果。

编辑:

对于那些问数组中内容是什么的人,我正在尝试找到最有效的方法来查找返回此函数中排序方向的参数。

https://stackblitz.com/edit/typescript-syhjq4

我正在使用reduce,但是由于sort函数无论如何都会对数组进行突变,所以我使用了带有突变的一些。

2 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,也许您可​​以通过首先将值的array减少为Set来实现所需的目的。

这意味着随后的find()如下所示仅对唯一值起作用(这避免了重复数组项上functionThatCalulatesResult()的冗余迭代和重新处理):

// Mock functionThatCalulatesResult() to illustrate this answers
// idea. The function returns truthy when value 5 encountered
function functionThatCalulatesResult(i) {
  console.log('visiting:', i )      
  if(i === 5) {
    return true;
  }  
}

var array = [1,2,3,1,3,1,5,6];

// Reducing array to unique set of values avoid reprocessing of 
// functionThatCalulatesResult() on duplicate values that don't 
// return truthy
var result = Array.from(new Set(array)).find(functionThatCalulatesResult);

console.log('result', result) 

答案 1 :(得分:0)

这很棘手,因为据我所知,使用标准的“功能”方法无法有效地做到这一点。

老实说,最好的方法是将命令式循环封装在一个函数中。 我知道这可能不是最令人满意的答案,但是我个人发现,当您有时使用命令式代码时,您的代码实际上变得更加简洁:

let map_find = (array, map_fn) => {
  for (let item of array) {
    let result = map_fn(array[i]);
    if (result) {
      return result;
    }
  }
}

// use map_find like it is super functional
const item = map_find(array, i => functionThatCalulatesResult(i));

(而且for (... of ...)看起来仍然比for循环好很多;))