Use PHP functions in JavaScript

JavaScript array_merge

Merges elements from passed arrays into one array

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
39
4041
42
43
44
4546
47
48
49
5051
52
53
54
5556
function array_merge () {
    // Merges elements from passed arrays into one array  
    // 
    // version: 1008.1718
    // discuss at: http://phpjs.org/functions/array_merge    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Nate
    // +   input by: josh
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: arr1 = {"color": "red", 0: 2, 1: 4}    // *     example 1: arr2 = {0: "a", 1: "b", "color": "green", "shape": "trapezoid", 2: 4}
    // *     example 1: array_merge(arr1, arr2)
    // *     returns 1: {"color": "green", 0: 2, 1: 4, 2: "a", 3: "b", "shape": "trapezoid", 4: 4}
    // *     example 2: arr1 = []
    // *     example 2: arr2 = {1: "data"}    // *     example 2: array_merge(arr1, arr2)
    // *     returns 2: {0: "data"}
    
    var args = Array.prototype.slice.call(arguments),
                            retObj = {}, k, j = 0, i = 0, retArr = true;    
    for (i=0; i < args.length; i++) {
        if (!(args[i] instanceof Array)) {
            retArr=false;
            break;        }
    }
    
    if (retArr) {
        retArr = [];        for (i=0; i < args.length; i++) {
            retArr = retArr.concat(args[i]);
        }
        return retArr;
    }    var ct = 0;
    
    for (i=0, ct=0; i < args.length; i++) {
        if (args[i] instanceof Array) {
            for (j=0; j < args[i].length; j++) {                retObj[ct++] = args[i][j];
            }
        } else {
            for (k in args[i]) {
                if (args[i].hasOwnProperty(k)) {                    if (parseInt(k, 10)+'' === k) {
                        retObj[ct++] = args[i][k];
                    } else {
                        retObj[k] = args[i][k];
                    }                }
            }
        }
    }
    return retObj;}
external links: original PHP docs | raw js source

Examples

» Example 1

Running

1
2
3
arr1 = {"color": "red", 0: 2, 1: 4}
arr2 = {0: "a", 1: "b", "color": "green", "shape": "trapezoid", 2: 4}
array_merge(arr1, arr2)

Should return

1
{"color": "green", 0: 2, 1: 4, 2: "a", 3: "b", "shape": "trapezoid", 4: 4}

» Example 2

Running

1
2
3
arr1 = []
arr2 = {1: "data"}
array_merge(arr1, arr2)

Should return

1
{0: "data"}

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_merge goodness in JavaScript.

Comments

Add Comment
Use:
[CODE]
your_stuff('here');
[/CODE]
for proper code formatting
By submitting code here you are allowing us to use it in php.js hence dual licensing it under the MIT and GPL licenses

Gravatar
Brett Zamir
Mar 26th Permalink

q  @josh: And, btw, if you are only dealing with simple numeric arrays, to do that in simple JS style, just do

var arr3 = arr1.concat(arr2);



See also https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/concat

Gravatar
Brett Zamir
Mar 26th Permalink

q  @josh: Thanks for pointing out the bug. Fixed in git: http://github.com/kvz/phpjs/raw/master/functions/array/array_merge.js . The code had problems when all arrays were input, but also with numeric renumbering. Sorry for the trouble on that one, but it should be working now.

Gravatar
josh
Mar 26th Permalink

q  this doesn't return the expected values...

arr1 = Array('zero','one','two','three');
arr2 = Array(4,5,6,7);
arr3 = array_merge(arr1,arr2);

php does this:

arr3: Array
(
[0] => zero
[1] => one
[2] => two
[3] => three
[4] => 4
[5] => 5
[6] => 6
[7] => 7
)



while js function does this:

0:
0: zero
1: one
2: two
3: three
1:
0: 4
1: 5
2: 6
3: 7


i can put two arrays into a bigger array in regular javascript... 9_9

Gravatar
Kevin van Zonneveld
8 Oct '09 Permalink

q  @ Subhasis: But don't we already have an array_merge_recursive function?

Gravatar
Brett Zamir
27 Sep '09 Permalink

q  @Matheus : That probably just means that the function is returning an object and you are trying to view it as a string (like in an alert). Why does the function return an object? In order to allow for associative arrays, we must use objects in such cases (though this function tries to return a bona fide array if possible).

Gravatar
Matheus
26 Sep '09 Permalink

q  This funcion don't work. It's returning [object Object]

Gravatar
Subhasis
1 Dec '08 Permalink

q  @Kevin,
actually its not the &quot;array_merge&quot; function but rather the &quot;array_merge_recursive&quot; function.. it can accept nested array/object which it will merge recursively... one
point to walk over is it gives preference to array object.. so it wont overwrite array/objects if the master array has it... e.g 'cc':[6,8], 'cc':8; o/p: [6,8]..

------------------------------------------
Subhasis
http://weread.com

Gravatar
Kevin van Zonneveld
25 Nov '08 Permalink

q  @ Nate: Thanks dude!
@ Subhasis Deb: Could you please tell us how your function would be the better implementation?

Gravatar
Subhasis Deb
25 Nov '08 Permalink

q  Following is my version of array_merge (compact):

/***
* Simulate php array_merge function
*
* @param {Object/Array} arr1
* @param {Object/Array} arr2
* var a1 = {'aa':100, 'bb':2, 'cc':[6,7], 'dd':[12,13], 'ee':{'15':15,'16':16}};
* var b1 = {'xx':101, 'bb':5, 'cc':8, 'dd':[14,15], 'ee':{'17':17,'18':18}};
* var c = array_merge(a1, b1);
* console.log(c) [in firebug]
* Output: {'aa':100, 'bb': 5, 'cc':[6,7], 'dd':[12,13,14,15], 'ee':{'15':15,'16':16,'17':17,'18':18}, 'xx':101}
*/
array_merge : function(arr1, arr2){
if((arr1 &amp;&amp; (arr1 instanceof Array)) &amp;&amp; (arr2 &amp;&amp; (arr2 instanceof Array))){
for (var idx in arr2) {
arr1.push(arr2[idx]);
}
}else if((arr1 &amp;&amp; (arr1 instanceof Object)) &amp;&amp; (arr2 &amp;&amp; (arr2 instanceof Object))){
for(var idx in arr2){
if(idx in arr1){
if (typeof arr1[idx] == 'object' &amp;&amp; typeof arr2 == 'object') {
arr1[idx] = array_merge(arr1[idx], arr2[idx]);
}else{
arr1[idx] = arr2[idx];
}
}else{
arr1[idx] = arr2[idx];
}
}
}
return arr1;
},

Gravatar
Nate
19 Nov '08 Permalink

q  Neither &quot;ct&quot; nor &quot;retArr&quot; are declared with &quot;val&quot;, and therefore create unnecessary global variables. I suggest that &quot;retArr&quot; be declared at the top and &quot;ct&quot; be declared after the code:
[CODE=&quot;Javascript&quot;]
if (retArr) {
return args;
}
[/CODE]
The reason for this is because the function sometimes finishes before ever reaching the part that uses &quot;ct&quot;, and therefore, it could waste a slight amount of time declaring a variable that it didn't end up using. The same is also true for &quot;retObj&quot;, &quot;k&quot;, and &quot;j&quot;. But it's just a suggestion.


Contribute a New function