Merge two arrays, preserve unique elements and sort in jQuery

var Arr1 = [1,3,4,5,6]; var Arr2 = [4,5,6,8,9,10]; 

I try to combine these two arrays and the output goes [1,3,4,5,6,4,5,6]

I used $.merge(Arr1, Arr2); this part to combine them. Using alert, I see a merged array as shown above.

Now my question is: how can I get the following output: [1,3,4,5,6,8,9,10]

i.e. Items must be unique and also sorted in the same way as I mentioned.

Please, help.

+7
javascript jquery arrays merge
source share
6 answers

You can use Array.prototype.sort () to do real digital sorting and use Array.prototype.filter () to return unique elements.

You can wrap it in an assistant like this:

 var concatArraysUniqueWithSort = function (thisArray, otherArray) { var newArray = thisArray.concat(otherArray).sort(function (a, b) { return a > b ? 1 : a < b ? -1 : 0; }); return newArray.filter(function (item, index) { return newArray.indexOf(item) === index; }); }; 

Note that the custom sort function only works with numeric elements, so if you want to use it for strings or mix strings with numbers, you need to update it off course to take these scenarios into account, although the rest should not change much.

Use it as follows:

 var arr1 = [1, 3, 4, 5, 6]; var arr2 = [4, 5, 6, 8, 9, 10]; var arrAll = concatArraysUniqueWithSort(arr1, arr2); 

arrAll will now be [1, 3, 4, 5, 6, 8, 9, 10]


DEMO - merge 2 arrays, sort and delete duplicates


There are many ways to do this, I am sure. It was just the shortest thing I could think of.

+9
source share

merge two or more arrays + remove duplicates + sort ()

 jQuery.unique([].concat.apply([],[[1,2,3,4],[1,2,3,4,5,6],[3,4,5,6,7,8]])).sort(); 
+3
source share

It looks like work for Array.prototype.indexOf

 var arr3 = arr1.slice(), // clone arr1 so no side-effects i; // var i so it not global for (i = 0; i < arr2.length; ++i) // loop over arr2 if (arr1.indexOf(arr2[i]) === -1) // see if item from arr2 is in arr1 or not arr3.push(arr2[i]); // it not, add it to arr3 arr3.sort(function (a, b) {return a - b;}); arr3; // [1, 3, 4, 5, 6, 8, 9, 10] 
0
source share

Using underscore.js:

 _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]).sort(function(a,b){return ab}); => [1, 2, 3, 10, 101] 

This example is taken directly from underscore.js , the popular JS library that complements jQuery

0
source share
 a = [1, 2, 3] b = [2, 3, 4] $.unique($.merge(a, b)).sort(function(a,b){return ab}); -> [1, 2, 3, 4] 

Update: This is a bad idea because the β€œunique” function is not intended to be used on numbers or strings. However, if you need, the sort function should be used to use the new comparator, since by default it sorts lexicographically.

0
source share

I did it as follows, where t1 and t2 are my two tables.

The first command puts the values ​​of table t2 in t1. The second command removes duplicate values ​​from the table.

 $.merge(t1, t2); $.unique(t1); 
0
source share

All Articles