Here's a simple task: Find the minimum of an array. Example array: [ -52, 56, 30, 29, -54, 0, -110 ]. I'm trying to solve this with the 'reduce()' higher-order function, WITHOUT using Math.min() or any sorting algorithms/functions. So far I've got this code, x is doing fine and having the right values, but the final iteration returns a weird version of the input array, instead of the minimum:
const input = [-52, 56, 30, 29, -54, 0, -110]
var min = function (list) {
return list.reduce((x, y) => {
if (y < x) x = y;
return x;
}, 0);
}
console.log(min(input))
You need to initialize the reduce function with the first element of the array not 0.
var min = function (list) {
return list.reduce((x, y) => {
if (y < x) x = y;
return x;
}, list[0]);
}
console.log(min([1, 5, 3]))