|

Easy Way of Finding Max Element of an Array

Until 2015 we need apply method to apply Math.max function to all elements of an array. ES6 destructing feature, announced at 2015, gives us an unpacked version of an array so that it makes using “apply” unnecessary.

function maxElement(arr) {
 let max = Math.max.apply(null, arr)
 return max;
}

let result = maxElement([7, 5, 33, 3]);
console.log(result)
function maxElement(arr) {
 // Using Rest parameter gives us an unpacked version of the array.
 let max = Math.max(...arr)
 return max;
}

let result = maxElement([7, 5, 33, 3]);
console.log(result)

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *