phpjs
Version:
71 lines (58 loc) • 2.07 kB
Markdown
layout: page
title: "JavaScript array_reduce function"
comments: true
sharing: true
footer: true
alias:
- /functions/view/array_reduce:333
- /functions/view/array_reduce
- /functions/view/333
- /functions/array_reduce:333
- /functions/333
<!-- Generated by Rakefile:build -->
A JavaScript equivalent of PHP's array_reduce
{% codeblock array/array_reduce.js lang:js https://raw.github.com/kvz/phpjs/master/functions/array/array_reduce.js raw on github %}
function array_reduce (a_input, callback) {
// From: http://phpjs.org/functions
// + original by: Alfonso Jimenez (http://www.alfonsojimenez.com)
// % note 1: Takes a function as an argument, not a function's name
// * example 1: array_reduce([1, 2, 3, 4, 5], function (v, w){v += w;return v;});
// * returns 1: 15
var lon = a_input.length;
var res = 0,
i = 0;
var tmp = [];
for (i = 0; i < lon; i += 2) {
tmp[0] = a_input[i];
if (a_input[(i + 1)]) {
tmp[1] = a_input[(i + 1)];
} else {
tmp[1] = 0;
}
res += callback.apply(null, tmp);
tmp = [];
}
return res;
}
{% endcodeblock %}
- [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/array/array_reduce.js)
Please note that php.js uses JavaScript objects as substitutes for PHP arrays, they are
the closest match to this hashtable-like data structure.
Please also note that php.js offers community built functions and goes by the
[McDonald's Theory](https://medium.com/what-i-learned-building/9216e1c9da7d). We'll put online
functions that are far from perfect, in the hopes to spark better contributions.
Do you have one? Then please just:
- [Edit on GitHub](https://github.com/kvz/phpjs/edit/master/functions/array/array_reduce.js)
### Example 1
This code
{% codeblock lang:js example %}
array_reduce([1, 2, 3, 4, 5], function (v, w){v += w;return v;});
{% endcodeblock %}
Should return
{% codeblock lang:js returns %}
15
{% endcodeblock %}
### Other PHP functions in the array extension
{% render_partial _includes/custom/array.html %}