This problem was asked by Uber.
Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].
function aryTransform(input) {
return input.map((el, index, ary) => {
const everything = ary.reduce((acc, curr) => {
return acc * curr
})
return everything / el
})
}
console.log(aryTransform([1,2,3,4,5])) //[ 120, 60, 40, 30, 24 ]
console.log(aryTransform([3,2,1])) //[ 2, 3, 6 ]
Follow-up: what if you can't use division?
function aryTransformWIthoutDivision(input) {
return input.map((el, index, ary) => {
return ary.reduce((acc, curr, rIndex) => {
if (curr == el) {
return acc
} else {
return acc * curr
}
}, 1)
})
}
console.log(aryTransformWIthoutDivision([1,2,3,4,5])) //[ 120, 60, 40, 30, 24 ]
console.log(aryTransformWIthoutDivision([3,2,1])) //[ 2, 3, 6 ]
Hello, I tried to solve it with for loop but it doesn't work clearly, could you please tell what's wrong and how I can fix that
function arraySumtionWithoutI(arr){
for(var i=1; i<= arr.length; i++){
var newArr = arr.reduce((a,b) => {
return a*b
})
console.log(newArr/i)
}
}
console.log(arraySumtionWithoutI([1, 2, 3, 4, 5]))
console.log(arraySumtionWithoutI([3, 2, 1]))