Guest User

Untitled

a guest
Dec 14th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. // Function that returns the index of element in array where the sum of all of the other elements to its left
  2. // are equal to the sum of elements to its right.
  3. // e.g. in [1, 3, 5, 9, 7, 2] the answer would be index of 3 (ie the number 9)
  4. // since the elements to its left sum up to 9 (1+3+5=9)
  5. // and also the elements to its right (7+2=9)
  6. // if not matching element found -1 is returned.
  7.  
  8. const middle = (numArray) => (
  9. numArray.findIndex((el, idx) => {
  10. const data = numArray.reduce((obj, el, i) => {
  11. // sum of elements to the left
  12. if(i < idx) {
  13. obj.sumLeft += el;
  14. return obj;
  15. }
  16. // sum of elements to the right
  17. if(i > idx) {
  18. obj.sumRight += el;
  19. return obj;
  20. }
  21. return obj;
  22. }, { sumLeft: 0, sumRight: 0 });
  23.  
  24. return data.sumLeft === data.sumRight
  25. })
  26. );
  27.  
  28. // eg
  29. const numbers = [1, 2, 3, 4, 10, 7, 3];
  30. middle(numbers); // => 4
Add Comment
Please, Sign In to add comment