Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Given an array of elements, find result array where each elements are product of all elements except for the current element.
- Eg: [1,2,3,4,5] result array to be [ 120, 60, 40, 30, 24 ]
- */
- function productArray(arr){
- let zeroFlag = false,
- zIndex = null,
- resultArray = [];
- let productOfElements = arr.reduce( (accum, currValue, currIndex) =>{
- //Handling zero element setting zero flag if present
- if(currValue === 0) {
- zeroFlag = true;
- zIndex = currIndex;
- }
- //the product would be zero if any element is zero
- return currValue !== 0 ? accum * currValue : accum * 1;
- }, 1);
- if(zeroFlag) {
- resultArray = Array(arr.length).fill(0);
- resultArray.splice(zIndex, 1, productOfElements);
- }
- else {
- arr.map( (currValue, idx) => {
- resultArray.push(productOfElements / arr[idx]);
- });
- }
- return resultArray;
- }
- productArray([1,2,3,4,5])
Add Comment
Please, Sign In to add comment