Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (1.5k points)
recategorized by
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

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...