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
function array_merge () {
    // Merges elements from passed arrays into one array  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/array_merge    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Nate
    // -    depends on: is_int
    // %          note: Relies on is_int because !isNaN accepts floats     
    // *     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: {1: "data"}
    
    var args = Array.prototype.slice.call(arguments);
    var retObj = {}, k, j = 0, i = 0;    var retArr;
    
    for (i=0, retArr=true; i < args.length; i++) {
        if (!(args[i] instanceof Array)) {
            retArr=false;            break;
        }
    }
    
    if (retArr) {        return args;
    }
    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 (this.is_int(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
{1: "data"}

Dependencies

In order to use this function, you also need:

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
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 "array_merge" function but rather the "array_merge_recursive" 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 && (arr1 instanceof Array)) && (arr2 && (arr2 instanceof Array))){
for (var idx in arr2) {
arr1.push(arr2[idx]);
}
}else if((arr1 && (arr1 instanceof Object)) && (arr2 && (arr2 instanceof Object))){
for(var idx in arr2){
if(idx in arr1){
if (typeof arr1[idx] == 'object' && 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 "ct" nor "retArr" are declared with "val", and therefore create unnecessary global variables. I suggest that "retArr" be declared at the top and "ct" be declared after the code:

1
2
3
if (retArr) {
        return args;
    }

The reason for this is because the function sometimes finishes before ever reaching the part that uses "ct", 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 "retObj", "k", and "j". But it's just a suggestion.


Contribute a New function