Looking for the best approach to solve this array problem.
[ 1, -1, -1, -1, 1, -1, 1, 1 ]
I'm debating between using the reduce method, a do..while loop, or possibly something else.
The task involves looping through the array and summing up as I go. If the sum equals 0
, then add those elements to a new array.
For instance, if the first two elements in the array result in 0
when added together, like [1, -1], they should be placed into a new array:
[[1, -1], [-1, -1, 1, -1, 1, 1]]
My current attempt uses the reduce
method:
let hikeArr = [ 1, -1, -1, -1, 1, -1, 1, 1 ];
let newArr = hikeArr.reduce((a, b) => {
let sum = a + b;
if( sum == 0) {
a.push(b)
}
return a;
}, []);
console.log("newArr", newArr);
Any suggestions on a more efficient approach?