Home > Net >  i want the below javascript program to give the output in array format, how can i do that?
i want the below javascript program to give the output in array format, how can i do that?

Time:08-25

I wrote this javascript program to find sum of array elements, also i got the answer, but i want the answer to be in array format , how i can do that ?

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

for(let i=0; i<=arr.length-1; i  ){
    sum=sum arr[i];
    console.log(sum);
  }

here is the output i am getting

**output ==>** 
1 
3
6
10
15

this is the output i want

**expected output ==>**   [1,3,6,10,15]

CodePudding user response:

Use javascript array.map function()

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

var roots = arr.map(function(num) {
    sum=sum num;
    return sum;
});
console.log(roots);

CodePudding user response:

    let arr=[1,2,3,4,5];
let sum=0;
var newarr = []
for(let i=0; i<=arr.length-1; i  ){
    sum=sum arr[i];
newarr.push(sum)
    
  }
console.log(newarr);

CodePudding user response:

The easiest way is to either store the running values of sum into arr (or into another array), then using console.log, which will format an array for you automatically.

Below is an implementation.

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

for(let i=0; i<=arr.length-1; i  ){
    sum=sum arr[i];
    arr[i] = sum;
}

console.log(arr);

CodePudding user response:

 let arr=[1,2,3,4,5];
    function sum(nums) {    
    for(let i=1; i< nums.length; i  ){
        nums[i] = nums[i]   nums[i-1];
      }
      return nums;
    }
    
    console.log(sum(arr));

No need to create new array just update the existing one with new values.

CodePudding user response:

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

for (let i = 1; i <= arr.length - 1; i  ) {
  sum.push(sum[i - 1]   arr[i]);
}

console.log(sum);

CodePudding user response:

Try this.

let arr=[1,2,3,4,5];
let sum=0;
let arrayOfSum=[];
for(let i=0; i<=arr.length-1; i  ){
    sum=sum arr[i];
    arrayOfSum.push(sum);
}
console.log(arrayOfSum);
  • Related