I'm working on sharpening my JS skills and working through some problems on CodeSignal. I'm working on the following problem:
Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.
So for example, given the array [2,3,5,10,2,4] I would want to do the following:
2 * 3 = 6
5 * 10 = 50
2 * 4 = 8
Then I want to return the largest product, in this case 50.
My approach is to iterate with a for loop, multiply i * i + 1, push the product into a new array, then increment the for loop by 2 so I can multiple the next two numbers in the array. When I'm done pushing into the new array I want to use Math.max and call it on the array of numbers to return the largest product.
Math.max does not work on arrays so I will use the ES6 spread operator and do something like this:
Math.max(...products);
Here's what I have so far that isn't working:
function adjacentElementsProduct(inputArray) {
var products = [];
for(var i = 0; i <= inputArray.length; i = i + 2) {
products.push(inputArray[i] * inputArray[i + 1]);
};
// Correctly logs elements of products array
console.log(products);
// NaN error
console.log(Math.max(...products));
return Math.max(...products);
}
Does this NaN error have to do with attempting to call Math.max and the spread operator before the for loop finishes and has the values pushed into the array?