JSFiddle - React, Tailwind, and code Playground

getProductsOfAllIntsExceptAtIndex

by Varayut Lerdkanlayanawat

JavaScript

// https://www.interviewcake.com/question/javascript/product-of-other-numbers
function getProductsOfAllIntsExceptAtIndex(originalArray) {
	const result = [];
  
  let beforeValue = 1;
	// Move forward and calculate the value before each index
  for (let i = 0; i < originalArray.length; i++) {
  	result[i] = beforeValue;
    beforeValue *= originalArray[i];
	}
  
  // Move backward and calculate the value after each index
  let afterValue = 1;
  for (let i = originalArray.length - 1; i >= 0; i--) {
  	result[i] *= afterValue;
    afterValue *= originalArray[i];
	}
  
  return result;
}

console.log(getProductsOfAllIntsExceptAtIndex([1, 7, 3, 4]));