Intellipaat Back

Explore Courses Blog Tutorials Interview Questions

Explore Tech Questions and Answers

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

0 votes
2 views
by (1.5k points)
I am having difficulty in finding out the sum of an array in Javascript. Can someone help me with the code and explanation?

1 Answer

0 votes
by (1.4k points)

There are n numbers of ways to find the sum of array in Java some of them are mentioned below: 

  • Method 1 : Using built-in reduce() 

Example: 

function all(arr) { 

  if(!Array.isArray(arr)) return; 

  return arr.reduce((a, v)=>a + v); 

} 

  • Using for loop 

Example: 

function all(arr) { 

  if(!Array.isArray(arr)) return; 

  let totalNumber = 0; 

  for (let i=0,l=arr.lengthi<l; i++) { 

     totalNumber+=arr[i]; 

  } 

  return totalNumber; 

} 

  • Using while loop 

Example: 

function all(arr) { 

  if(!Array.isArray(arr)) return; 

  let allnum = 0i=-1; 

  while (++i < arr.length) { 

     allnum+=arr[i]; 

  } 

  return allnum; 

} 

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
0 answers
asked Feb 18, 2021 in Java by Harsh (1.5k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...