JavaScript array_map
Applies the callback to the elements in given arrays.
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 2526 27 28 29 3031 32 33 34 3536 37 38 | function array_map (callback) { // Applies the callback to the elements in given arrays. // // version: 909.322 // discuss at: http://phpjs.org/functions/array_map // + original by: Andrea Giammarchi (http://webreflection.blogspot.com) // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Brett Zamir (http://brett-zamir.me) // % note 1: Takes a function as an argument, not a function's name // % note 2: If the callback is a string, it can only work if the function name is in the global context // * example 1: array_map( function (a){return (a * a * a)}, [1, 2, 3, 4, 5] ); // * returns 1: [ 1, 8, 27, 64, 125 ] var argc = arguments.length, argv = arguments; var j = argv[1].length, i = 0, k = 1, m = 0; var tmp = [], tmp_ar = []; while (i < j) { while (k < argc){ tmp[m++] = argv[k++][i]; } m = 0; k = 1; if (callback){ if (typeof callback === 'string') { callback = this.window[callback]; } tmp_ar[i++] = callback.apply(null, tmp); } else { tmp_ar[i++] = tmp; } tmp = []; } return tmp_ar; } |
Examples
Running
1 | array_map( function (a){return (a * a * a)}, [1, 2, 3, 4, 5] ); |
Should return
1 | [ 1, 8, 27, 64, 125 ] |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have array_map goodness in JavaScript.
No comments yet. Be the first!

spread the word:
Use any PHP function in JavaScript
These kind folks have already donated: Anonymous and Shawn Houser.
<your name here>