Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Function that returns the index of element in array where the sum of all of the other elements to its left
- // are equal to the sum of elements to its right.
- // e.g. in [1, 3, 5, 9, 7, 2] the answer would be index of 3 (ie the number 9)
- // since the elements to its left sum up to 9 (1+3+5=9)
- // and also the elements to its right (7+2=9)
- // if not matching element found -1 is returned.
- const middle = (numArray) => (
- numArray.findIndex((el, idx) => {
- const data = numArray.reduce((obj, el, i) => {
- // sum of elements to the left
- if(i < idx) {
- obj.sumLeft += el;
- return obj;
- }
- // sum of elements to the right
- if(i > idx) {
- obj.sumRight += el;
- return obj;
- }
- return obj;
- }, { sumLeft: 0, sumRight: 0 });
- return data.sumLeft === data.sumRight
- })
- );
- // eg
- const numbers = [1, 2, 3, 4, 10, 7, 3];
- middle(numbers); // => 4
Add Comment
Please, Sign In to add comment