1

Im trying to take an array of numbers and finding the two adjacent numbers with the highest product. So created a function that multiplies the first two indexes od the array and pushes that product to a new array. My code works for the first index positions but stops and doesn't complete the remaining indexes. What am I doing wrong. This is a code signal practice exercise.

Test: inputArray: [3, 6, -2, -5, 7, 3] Output: [18, -12, 10]

function solution(inputArray) {
  var newArray = []
  for (var i = 0; i < inputArray.length; i++) {
    const indexOneAndTwoProduct = inputArray[0] * inputArray[1]
    newArray.push(indexOneAndTwoProduct)
    inputArray.shift()
  }
  return newArray
}

console.log(solution([3, 6, -2, -5, 7, 3]));
David
  • 208,112
  • 36
  • 198
  • 279
  • Welcome to Stack Overflow! This is a good opportunity for you to start familiarizing yourself with [using a debugger](https://stackoverflow.com/q/25385173/328193). When you step through the code in a debugger, which operation first produces an unexpected result? What were the values used in that operation? What was the result? What result was expected? Why? To learn more about this community and how we can help you, please start with the [tour] and read [ask] and its linked resources. – David Nov 29 '22 at 21:33
  • 2
    *At a glance* (and you should debug to observe this)... What do you expect `shift()` to do, and what effect do you expect that to have on `inputArray.length` (on which the loop is based)? – David Nov 29 '22 at 21:37

1 Answers1

1

It's a good practice do not modify the same array that you are iterating. I think that something like this could work:

function solution(inputArray) {
  const newArray = []
  for (let i = 0; i < inputArray.length - 1; i++) {
    const indexOneAndTwoProduct = inputArray[i] * inputArray[i + 1]
    newArray.push(indexOneAndTwoProduct)
  }
  return newArray
}

console.log(solution([3, 6, -2, -5, 7, 3]))
dawalberto
  • 96
  • 5