simplexity
simplexity

Reputation: 1557

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?

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.

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). Purely curious!

Upvotes: 2

Views: 356

Answers (3)

Lux
Lux

Reputation: 18240

You could simply use .map(). Basically your for loop is equivalent to this:

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. Also I wouldn't use .filter(e,i) => i === 0) but rather .pop() or [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:

function largestEach(arr) {
  return arr.map(e => Math.max(...e))
}

Upvotes: 4

P Ackerman
P Ackerman

Reputation: 2406

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

Upvotes: 2

dhilt
dhilt

Reputation: 20754

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

Upvotes: 2

Related Questions