jQuery API

jQuery.merge()

jQuery.merge( first, second ) Returns: Array

Description: Merge the contents of two arrays together into the first array.

  • version added: 1.0jQuery.merge( first, second )

    firstThe first array to merge, the elements of second added.

    secondThe second array to merge into the first, unaltered.

The $.merge() operation forms an array that contains all elements from the two arrays. The orders of items in the arrays are preserved, with items from the second array appended. The $.merge() function is destructive. It alters the first parameter to add the items from the second.

If you need the original first array, make a copy of it before calling $.merge(). Fortunately, $.merge() itself can be used for this duplication:

var newArray = $.merge([], oldArray);

This shortcut creates a new, empty array and merges the contents of oldArray into it, effectively cloning the array.

The arguments should be true Javascript Array objects; use $.makeArray if they are not.

Examples:

Example: Merges two arrays, altering the first argument.

$.merge( [0,1,2], [2,3,4] )

Result:

[0,1,2,2,3,4] 

Example: Merges two arrays, altering the first argument.

$.merge( [3,2,1], [4,3,2] )  

Result:

[3,2,1,4,3,2] 

Example: Merges two arrays, but uses a copy, so the original isn't altered.

var first = ['a','b','c'];
var second = ['d','e','f'];
$.merge( $.merge([],first), second);
      

Result:

["a","b","c","d","e","f"] 

Comments

  • Support requests, bug reports, and off-topic comments will be deleted without warning.

  • Please do post corrections or additional examples for jQuery.merge() below. We aim to quickly move corrections into the documentation.
  • If you need help, post at the forums or in the #jquery IRC channel.
  • Report bugs on the bug tracker or the jQuery Forum.
  • Discussions about the API specifically should be addressed in the Developing jQuery Core forum.
  • With jQuery 1.4, the two arguments don't have to be true Javascript Array objects.
    Remove or update the line "The arguments should be true Javascript Array objects; use $.makeArray if they are not.".