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

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

I am trying to do merge these two arrays and output coming is [1,3,4,5,6,4,5,6]

I have used $.merge(Arr1, Arr2); this piece to merge them. Using alert I can see the merged array like above.

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

i.e. the elements should be unique as well as sorted in the same manner I have mentioned.

Please help.

ntzm
  • 4,663
  • 2
  • 31
  • 35
Monibrata
  • 427
  • 4
  • 10
  • 25

9 Answers9

9

You can use Array.prototype.sort() to do a real numeric sort and use Array.prototype.filter() to only return the unique elements.

You can wrap it into a helper similar to 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 works with numeric elements only, so if you want to use it for strings or mix strings with numbers you have to update it off course to take those scenarios into account, though the rest should not change much.

Use it like this:

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 - concatenate 2 arrays, sort and remove duplicates


There is many ways of doing this I'm sure. This was just the most concise I could think off.

Nope
  • 22,147
  • 7
  • 47
  • 72
4

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

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

One line solution using just javascript.

var Arr1 = [1,3,4,5,6];

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

const sortedUnion = [... new Set([...Arr1,... Arr2].sort((a,b)=> a-b))]
console.log(sortedUnion)
Jeevan HS
  • 163
  • 6
  • While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Yunnosch Jun 29 '21 at 19:53
0

This looks like a job for Array.prototype.indexOf

var arr3 = arr1.slice(),              // clone arr1 so no side-effects
    i;                                // var i so it 's 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's not, add it to arr3
arr3.sort(function (a, b) {return a - b;});
arr3; // [1, 3, 4, 5, 6, 8, 9, 10]
Paul S.
  • 64,864
  • 9
  • 122
  • 138
0

Using underscore.js:

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

This example is taken directly from underscore.js, a popular JS library which complements jQuery

Jay
  • 1
  • 1
  • `[1, 2, 3, 101, 10]`, seems sorted incorrectly as OP also want the final result to be sorted. – Nope Mar 06 '14 at 00:16
0
a = [1, 2, 3]
b = [2, 3, 4]
$.unique($.merge(a, b)).sort(function(a,b){return a-b}); -> [1, 2, 3, 4]

Update: This is a bad idea, since the 'unique' function is not meant for use on numbers or strings. However, if you must then the sort function needs to be told to use a new comparator since by default it sorts lexicographically.

avoid3d
  • 620
  • 6
  • 12
  • Using this it is showing [1,10,3,4,5,5,6,6,8,9] whereas I need [1,3,4,5,6,8,9,10] – Monibrata Mar 05 '14 at 21:13
  • Haha, yeah the result is being sorted lexicographically, my bad. Although is it not the sort() function which is doing this? (does the sort function do its thing lexicographically) – avoid3d Mar 05 '14 at 21:19
0

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

The first command put the values of the table t2 to the t1. The second command removes the duplicate values from the table.

$.merge(t1, t2);
$.unique(t1);
0
function sortUnique(matrix) {
  if(matrix.length < 1 || matrix[0].length < 1) return [];
  const result = [];
  let temp, ele;
  while(matrix.length > 0) {
    temp = 0;
    for(let j=0; j<matrix.length; j++) {
      if(matrix[j][0] < matrix[temp][0]) temp = j;
    }
    if(result.length === 0 || matrix[temp][0] > result[result.length-1]) {
      result.push(matrix[temp].splice(0,1)[0]);
    } else {
      matrix[temp].splice(0,1);
    }
    if(matrix[temp].length===0) matrix.splice(temp, 1);
  }
  return result;
}

console.log(sortUnique([[1,4,8], [2,4,9], [1,2,7]]))
Vinit Khandelwal
  • 490
  • 8
  • 20
0

Using JavaScript ES6 makes it easier and cleaner. Try this:

return [...Arr1, ...Arr2].filter((v,i,s) => s.indexOf(v) === i).sort((a,b)=> a - b);

and there you have it. You could build it in a function like:

function mergeUniqueSort(Arr1, Arr2){
    return [...Arr1, ...Arr2].filter((v,i,s) => s.indexOf(v) === i).sort((a,b)=> a - b);
}

and that settles it. You can also break it down using ES6. Use a Spread Operator to combine arrays:

let combinedArrays = [...Arr1, ...Arr2]

then get the unique elements using the filter function:

let uniqueValues = combinedArrays.filter((value, index, self ) => self.indexOf(value) === index)

Lastly you now sort the uniqueValue object:

let sortAscending  = uniqueValues.sort((a-b) => a - b)   // 1, 2, 3, ....10
let sortDescending = uniqueValues.sort((b-a) => b - a)   // 10, 9, 8, ....1

So you could use any part, just in case.

halfer
  • 19,824
  • 17
  • 99
  • 186
Ande Caleb
  • 1,163
  • 1
  • 14
  • 35