This is a simple array sum function for javascript in only 89 bytes !
I could have done an array prototype, witch would have remove the "is array" check, but i wanted to do it this way.
function (a //This is the array you want to sum | |
,b //Placeholder used as a counter | |
,c //Placeholder used as the total value | |
,d){ //Placeholder used to store the array length | |
d=a.length; //Storing array length, it's used twice so its shorter this way | |
return d? //First we check if a is an array | |
function(){ //If so we start the sum function | |
for(b=c=0; //Initialising b (counter) and c (sum) | |
b<d; //While b is lower than d (array length) | |
c+=a[b++]); //We put in c the actual value of a then increment b | |
return c }() //To finish we return c | |
:!1 //If a wasn't an array we return false | |
} |
function(a,b,c,d){d=a.length;return d?function(){for(b=c=0;b<d;c+=a[b++]);return c}():!1} |
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE | |
Version 2, December 2004 | |
Copyright (C) 2011 GUILLAUME COSTE <@Guillaume_Coste> | |
Everyone is permitted to copy and distribute verbatim or modified | |
copies of this license document, and changing it is allowed as long | |
as the name is changed. | |
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE | |
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION | |
0. You just DO WHAT THE FUCK YOU WANT TO. |
{ | |
"name": "JavascriptArraySum", | |
"description": "As its name say, it's an array sum function for javascript", | |
"keywords": [ | |
"array", | |
"sum", | |
"arraysum", | |
"array sum", | |
"140bytes" | |
] | |
} |
<!DOCTYPE html> | |
<title>Javascript ArraySum</title> | |
<div>Expected value: <b>38.4foo</b></div> | |
<div>Actual value: <b id="ret"></b></div> | |
<script> | |
var arraySum = function (a,b,c,d){d=a.length;return d?function(){for(b=c=0;b<d;c+=a[b++]);return c}():!1} | |
//We can use any type of data inside the array : | |
document.getElementById( "ret" ).innerHTML = arraySum([4,9,6,7,12.4,'foo']) | |
</script> |
A really brittle (and naughty) solution:
f = function(a){return eval(a.join("+").replace(/[^+\-1-9\.]/g,0))}
@minikomi: It can be shortened like this:
function(a){return eval(a.join("+").replace(/[^+\d.-]/g,0))}
@tsaniel Unfortunately it gives weird results for arrays with strings which include numbers before letters eg.
[1,"3dogs"] => 30001
So maybe it wasn't the right way to go in the first place 💔
function (a,b){for(b in a){a[b]=(a[b]-0)};return eval(a.join("+").replace("NaN", 0))}
What about using map
? It's a bit different from your approach but this is how I would do it.
function(a,c){c=0;return a.map&&a.map(function(b){c+=isNaN(b)?0:b})&&c}
Another great work, but it will fail on empty arrays (it can be fixed with
a.reduce(f,0)
) and w/o any arguments.