Guest User

Untitled

a guest
Nov 19th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. /*
  2. Given an array of elements, find result array where each elements are product of all elements except for the current element.
  3. Eg: [1,2,3,4,5] result array to be [ 120, 60, 40, 30, 24 ]
  4. */
  5.  
  6. function productArray(arr){
  7. let zeroFlag = false,
  8. zIndex = null,
  9. resultArray = [];
  10.  
  11. let productOfElements = arr.reduce( (accum, currValue, currIndex) =>{
  12. //Handling zero element setting zero flag if present
  13. if(currValue === 0) {
  14. zeroFlag = true;
  15. zIndex = currIndex;
  16. }
  17. //the product would be zero if any element is zero
  18. return currValue !== 0 ? accum * currValue : accum * 1;
  19.  
  20. }, 1);
  21.  
  22. if(zeroFlag) {
  23. resultArray = Array(arr.length).fill(0);
  24. resultArray.splice(zIndex, 1, productOfElements);
  25. }
  26. else {
  27. arr.map( (currValue, idx) => {
  28. resultArray.push(productOfElements / arr[idx]);
  29. });
  30. }
  31.  
  32. return resultArray;
  33. }
  34.  
  35. productArray([1,2,3,4,5])
Add Comment
Please, Sign In to add comment