I have a requirement to add previous value of an array element with the current element and ignore zero value in between. I need this logic using javascript, Below is the example code:
var arr = [1,2,0,0,3,0,4];
// Output I need: [1,3,0,0,6,0,10];
Can we achieve something this?
Thanks
Below is the code that i am using, I am not able to ignore the zero value in the array list
var durations = [1, 4.5,0,0, 3];
var sum = 0;
var array = durations.map(value => sum += value);
console.log(array);
// Output I am getting: [ 1, 5.5, 5.5, 5.5, 8.5 ]
// Output I need: [1,5.5,0,0,8.5]
4
Answers
You can check the current value of loop in
.map()
and return 0 if the value is 0:here is the solution:
You can use something like this:
You could use the
&&
operator to either evaluate to 0 (when the first operand is 0) or an updated sum: