简体   繁体   English

有什么方法可以避免for循环? (ES6 / JavaScript)

[英]Any way to avoid a for loop? (ES6 / JavaScript)

Improving my algorithm knowledge using ES6 (I am fairly new to ES6) and wondering if there is any way (if at all performant) of avoiding a for loop in this largest of each array function I wrote? 使用ES6改进我的算法知识(我是ES6的新手),并想知道在我编写的每个数组函数中最大的避免for循环是否有任何方法(如果在所有方面)?

function largestEach(arr) {
   for(const [i,v] of arr.entries())
      arr[i] = v.sort((a,b) => b - a).filter((e,i) => i === 0);
   return arr.reduce((a,b) => a.concat(b));
}
largestEach([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

Console logs: [5, 27, 39, 1001] which is correct. 控制台日志: [5, 27, 39, 1001]这是正确的。

It is conceptual so there is no real use case I am using it for. 这是概念性的,所以我没有使用它的真实用例。 I am not against for loops just curious what my better options were in ES6 (or JS in general). 我不反对循环只是好奇我在ES6(或一般的JS)中更好的选择。 Purely curious! 纯粹好奇!

You could simply use .map() . 你可以简单地使用.map() Basically your for loop is equivalent to this: 基本上你的for循环等同于:

arr = arr.map(elem => elem.sort((a, b) => b - a).filter(e,i) => i === 0)

However the next thing thats interesting is that you don't have to specify the sort function in this case. 然而,接下来有趣的是在这种情况下你不必指定sort函数。 Also I wouldn't use .filter(e,i) => i === 0) but rather .pop() or [0] . 另外我不会使用.filter(e,i) => i === 0)而是.pop()[0]

So you could rewrite: 所以你可以改写:

arr = arr.map(elem => elen.sort()[0])

Next you could use Math.max , so you can rewrite your entire function: 接下来你可以使用Math.max ,这样你就可以重写整个函数:

function largestEach(arr) {
  return arr.map(e => Math.max(...e))
}
function largestEach(arr) {
   return arr.map(a => a.reduce((a, b) => Math.max(a, b)));
}
function largestEach(arr) {
   return arr.map((a)=> Math.max.apply(null, a))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM