admin管理员组

文章数量:1125579

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]

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]
Share Improve this question edited Jan 9 at 7:02 JSON Derulo 17.2k11 gold badges56 silver badges73 bronze badges asked Jan 9 at 6:56 HariHari 11 silver badge1 bronze badge New contributor Hari is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct. 0
Add a comment  | 

4 Answers 4

Reset to default 1

You can check the current value of loop in .map() and return 0 if the value is 0:

var arr = [1, 4.5, 0, 0, 3];
var sum = 0;

var result = arr.map(value => value ? sum += value : 0);

console.log(result);

You can use something like this:

let arr = [ 1, 2, 0, 0, 3, 0, 4 ];
let previous = arr[ 0 ];

for( let i = 1; i < arr.length; i ++ ) {
   if( arr[ i ] != 0 ) {            
      arr[ i ] = arr[ i ] + previous;
      previous = arr[ i ];
   }
}

console.log( arr );

You could use the && operator to either evaluate to 0 (when the first operand is 0) or an updated sum:

const sumUp = (arr, sum=0) => arr.map(value => value && (sum += value));

// Demo
const arr = [1, 4.5, 0, 0, 3];
const result = sumUp(arr);
console.log(result);

You could use Array#reduce() :

const arr = [1,2,0,0,3,0,4];

const r = arr.reduce((r, item) => (r.arr.push(item ? r.prev = item + (r.prev ?? 0) : item), r), {arr: []}).arr;

console.log(JSON.stringify(r));

本文标签: