Method 1: Using jQuery’s $.unique() (Deprecated)
This method uses jQuery’s deprecated $.unique() function which only works properly on DOM elements. It requires the array to be sorted first.
1 2 3 4 5 |
var array1 = [1, 2, 3, 4]; var array2 = [3, 4, 5, 6]; var combined = array1.concat(array2); var unique = $.unique(combined.sort()); console.log(unique); // [1, 2, 3, 4, 5, 6] |
Method 2: Using ES6 Set
The modern approach using JavaScript’s Set object which automatically stores unique values. The spread operator converts it back to an array.
1 2 3 4 |
var array1 = [1, 2, 3, 4]; var array2 = [3, 4, 5, 6]; var unique = [...new Set([...array1, ...array2])]; console.log(unique); // [1, 2, 3, 4, 5, 6] |
Method 3: Using jQuery’s $.grep()
This method filters the combined array using $.grep(), keeping only the first occurrence of each element by checking index positions.
1 2 3 4 5 6 7 |
var array1 = [1, 2, 3, 4]; var array2 = [3, 4, 5, 6]; var combined = array1.concat(array2); var unique = $.grep(combined, function(item, index) { return combined.indexOf(item) === index; }); console.log(unique); // [1, 2, 3, 4, 5, 6] |
Method 4: Using jQuery’s $.extend() with objects
This approach uses an object to store unique values (since object keys must be unique) and then converts back to an array.
1 2 3 4 5 6 7 8 9 10 |
var array1 = [1, 2, 3, 4]; var array2 = [3, 4, 5, 6]; var obj = {}; $.each(array1.concat(array2), function(_, value) { obj[value] = value; }); var unique = $.map(obj, function(value) { return value; }); console.log(unique); // [1, 2, 3, 4, 5, 6] |
Method 5: Using filter and indexOf
A pure JavaScript solution that filters the combined array, keeping only elements whose first occurrence matches the current index.
1 2 3 4 5 6 7 |
var array1 = [1, 2, 3, 4]; var array2 = [3, 4, 5, 6]; var combined = array1.concat(array2); var unique = combined.filter(function(item, index) { return combined.indexOf(item) === index; }); console.log(unique); // [1, 2, 3, 4, 5, 6] |
Method 6: Using reduce
This method builds the unique array by checking and accumulating only new elements using the reduce function.
1 2 3 4 5 6 7 |
var array1 = [1, 2, 3, 4]; var array2 = [3, 4, 5, 6]; var unique = array1.concat(array2).reduce(function(acc, curr) { if (acc.indexOf(curr) === -1) acc.push(curr); return acc; }, []); console.log(unique); // [1, 2, 3, 4, 5, 6] |
Method 7: Using jQuery’s $.merge() and custom unique function
This combines jQuery’s array merging with a custom function that checks for first occurrences using $.inArray.
1 2 3 4 5 6 7 8 9 10 11 |
function getUnique(array) { return $.grep(array, function(el, index) { return index === $.inArray(el, array); }); } var array1 = [1, 2, 3, 4]; var array2 = [3, 4, 5, 6]; var combined = $.merge($.merge([], array1), array2); var unique = getUnique(combined); console.log(unique); // [1, 2, 3, 4, 5, 6] |