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!
return arr.map(v => Math.max(...v));-Infinityfor them, which is better than what the function in the question does in that case (where the output simply skips over any empty arrays, returning an array of different length to the input).