Is there a native Javascript method that returns the sum of the elements of an Array ? How does array_sum() do in PHP

Asked

Viewed 171 times

3

I would like to add the elements of an Array. As the example below:

array_soma = [5, 4, 3, 2, 1];
let resultado = metodo_somador(array_soma);

//Gostaria que nesse console retornasse o valor de 15
console.log(resultado);

  • There in the example, the methodo_adder() would be a method native of JS (I couldn’t find and I don’t know if it exists).
  • However, would not like to create a function, with loops, just to do this.
  • In the PHP there is the array_sum() that is native and returns this sum of the elements of an Array.

Thank you for your attention. Thank you!

3 answers

4

When something is that simple I really don’t see any reason to exist native and probably the developers of Ecmascript (aka Javascript) probably "agree", not that they haven’t created functions for trivial things in other cases, but it probably depends on odd factors and decisions that are beyond our understanding, the staff of the https://php.net is a community, they like to fill functions, even for trivial things, because that’s how that community thinks (remembering that not all were good devs in the early versions of PHP, a lot of talk on the internet and jokes confirm the problems).

Not exists in Javascript nothing native to tell, you can use Array.reduce, but understanding the basics helps a lot, a simple for you would achieve a similar result and with for still has better performance to perform multiple operations, something like:

var array_soma = [5, 4, 3, 2, 1];
var resultado = 0;

for (var i = array_soma.length - 1; i >= 0; i--) {
    resultado += array_soma[i];
}

console.log(resultado);

You don’t have to expect there to be a function for every trivial thing you need, if it is simple then use the simple, if you will even use this function in a number of different places and want to facilitate, then do something like:

function array_sum(arr) {
    let resultado = 0;

    for (var i = arr.length - 1; i >= 0; i--) {
        resultado += arr[i];
    }

    return resultado;
}

In use would be:

var array_soma = [5, 4, 3, 2, 1];
var resultado = array_sum(array_soma);

console.log(resultado);


function array_sum(arr) {
    let resultado = 0;

    for (var i = arr.length - 1; i >= 0; i--) {
        resultado += arr[i];
    }

    return resultado;
}


Benchmark (performance test)

I performed a local performance test, via Nodejs, which does not have so much interference from other processes, see the result:

Array.reduce x 135,434,338 ops/sec 0.37% (94 runs sampled)

Simple for x 146,437,628 ops/sec 0.60% (94 runs sampled)

For into Function x 145,747,268 ops/sec 0.34% (93 runs sampled)

Fastest is Simple for

Even the inside of a function managed 10,000,000 operations per second more than the Array.reduce.

The "online" test is not so reliable, but anyway you can try and see the difference in https://jsbench.me/8rk60td9hs/ (online test), Chrome result:

benchmark no navegador

  • Thank you, Guilherme Nascimento. But the question of For I understand. It’s quite simple to do. I would just like to know if there is something similar to PHP array_sum(). If I were to do it with, I would certainly have done it here. The point is, I’d like to do it with native things. Lately I’m trying to use more of the native language things to learn more.

  • @Jason-Theinternship. I understood your question perfectly, and the purpose of the answer is precisely this, why a native function for something so trivial? If it is so simple to do it in hand, it already solves and if you are going to use such a function many times then write your function yourself, as I showed in the answer. PS: If it existed native or if it exists one day I will edit the answer and add this.

  • I noticed that in JS there are not as many native methods as PHP. But it’s just my beginner opinion.

  • But, William, what’s wrong with using native functions? I believe it requires far fewer lines of code and is something that was created specifically for that. So create something that already exists something else that already does that ?

  • 1

    @Jason-Theinternship. precisely because we don’t need so many native methods, PHP only does it for convenience or because someone from the maintainer community thought it was cool, but in practice there’s a lot that’s trivial, by the way has some functions in PHP that are not as good as they appear and round and a half we have to write something in hand.

  • I understand, William. I appreciate the idea.

  • 1

    @Jason-Theinternship. I didn’t say it’s a problem to use the native, I didn’t say it at any point, I’m saying it’s something trivial to be added to a browser’s javascript engine, it’s so simple that developers should also agree, don’t have to do a function for every simploria thing, it’s raining in the wet. php only does this because it is a community full of people who want to facilitate what is not difficult and complicate what was easy... yes the PHP Devs community is not good.

  • I found the issue of array_sum in PHP a formidable and super useful thing for its purpose. As well as other native functions that facilitate a lot.

  • @Jason-Theinternship. but it is trivial, because what you seek is to solve something that is already simple, I find a lot of great things, in PHP and outside of it, just as I find a lot of horrible things in PHP and outside of it, one thing is you like, another thing is to be so simple that it doesn’t even need to exist native, when you start to fall in love with real programming (understand complex algorithms and like it), you will use the native when it exists whenever possible and use something that writes on the hand with your knowledge and you will find this combination great too.

  • I agree, William. In my case it is really a simple thing. My question is only whether it exists or not. I’d like to know if there’s anything specific for that. But if there isn’t, doing it with a For wouldn’t be a problem.

  • It’s because as a beginner, I like to learn most of the possible syntax of language. But your way of thinking isn’t wrong. That my case would be.

  • @Jason-Theinternship. I understand that you are a beginner and so my answer is great for this case, because it explains good things for beginners and for those who want to evolve.

Show 7 more comments

3

Another version for Guilherme to put in the benchmarks :D

  var i = arr.length;  // use let se o ambiente for moderno
  var sum = 0;        
  while (i--) sum += arr[i];

Following demonstration:

var array_soma = [5, 4, 3, 2, 1];
var resultado = array_sum(array_soma);

console.log(resultado);


function array_sum(arr) {
  var i = arr.length;  // use let se o ambiente for moderno
  var sum = 0;        
  while (i--) sum += arr[i];
  return sum;
}

3


You can use the reduce and add the current element to the "previous sum".

array_soma = [5, 4, 3, 2, 1];
let resultado = array_soma.reduce((acumulador, valorAtual) => acumulador + valorAtual, 0);

console.log(resultado);

However, this method may even be slower than using a "simple for". There is this simple performance test to compare both.

Documentation of reduce: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

This method is not specifically for "adding up". Perhaps it would be easier for you to write your own sum if it has to be used in more places (although it is actually a "simple for"). The method reduce exists in several languages and the goal of it is actually to "reduce" an array to an object.

  • 1

    I have a humble opinion from a beginner. Sometimes I think PHP has a much more case-specific native method than JS. Maybe my opinion is because I’m a beginner and I don’t know both languages in the background.

  • This method is not specifically for "adding up". Perhaps it would be easier for you to write your own sum if it has to be used in more places (although it is actually a "simple for"). The method reduce exists in several languages and the goal of it is actually to "reduce" an array to an object.

  • Yeah, in case it wouldn’t be more or less like the PHP array_sum.

  • Could you explain why the reduce is slower than the for.

  • The reduce is being faster in Chrome.

  • Your answer, with the use of reduce, was the one that came closest to my need shown in the question. Thank you!

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.