What Is the jQuery $.merge() Method?

The jQuery $.merge() method is a utility function designed to combine the contents of two arrays into a single array. This article explains the core purpose of $.merge(), how its destructive nature works on the target array, the syntax required to implement it, and how it handles array-like objects alongside standard JavaScript arrays.

Purpose of jQuery $.merge()

The primary purpose of the $.merge() method is to append all elements from a second array (or array-like object) onto the end of a first array. Unlike many standard array combination methods, $.merge() modifies the first array directly in place rather than creating a brand-new array from scratch.

Basic Syntax

$.merge(firstArray, secondArray);
  • firstArray: The target array that receives the new elements. This array is modified directly.
  • secondArray: The source array containing the elements to append. This array remains unchanged.

Key Behaviors and Characteristics

  1. In-Place Mutation: The first array passed to $.merge() is mutated. If you need to preserve the original first array, you must clone it before merging:

    var original = [1, 2];
    var additional = [3, 4];
    var combined = $.merge($.merge([], original), additional);
  2. No Duplicate Removal: $.merge() does not filter out duplicate values. If both arrays share identical elements, those elements will appear multiple times in the resulting array. To remove duplicates, you can use jQuery's $.uniqueSort() method on DOM element arrays or native JavaScript Set for primitive values.

  3. Support for Array-Like Objects: Beyond regular JavaScript arrays, $.merge() can operate on array-like objects that possess a .length property and indexed values, such as a DOM NodeList or a function's arguments object.

Code Example

var fruits = ["apple", "banana"];
var vegetables = ["carrot", "spinach"];

// Merge vegetables into fruits
$.merge(fruits, vegetables);

console.log(fruits); 
// Output: ["apple", "banana", "carrot", "spinach"]

console.log(vegetables); 
// Output: ["carrot", "spinach"] (remains unmodified)

jQuery $.merge() vs. Native JavaScript concat()

While native JavaScript provides Array.prototype.concat(), there is a functional difference:

  • concat() returns a completely new array without changing either of the input arrays.
  • $.merge() modifies the first array directly, making it useful in legacy codebases or performance-sensitive scenarios where reallocating memory for a new array is undesirable.