skip to Main Content

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


  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);
    Login or Signup to reply.
  2. here is the solution:

    var durations = [1, 4.5, 0, 0, 3];
    var sum = 0;
    
        var array = durations.map((value) => {
          if (value === 0) {
            return value;
          }
          return (sum += value);
        });
        
        console.log(array);
    
    Login or Signup to reply.
  3. 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 );
    Login or Signup to reply.
  4. 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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search