How to find unique records from two different array in jquery or javascript?

后端 未结 5 1049
不思量自难忘°
不思量自难忘° 2021-01-05 15:16

I want to get unique values from two different arrays.

Two arrays are as below in JavaScript:



        
5条回答
  •  忘掉有多难
    2021-01-05 15:47

    I think you really meant to write:

    
    

    In any case, you can sort the arrays and get the values from one that aren't in the other and vice versa, then concatenate the two sets into one. You seem spoilt for choice, so here's a nice basic javascript version that should work in most browsers. Using new features of the latest browsers is certain to fail in older browsers.

    // Compares a to b. Returns all the elements in a that are not in b
    // If c provided, add unique elements to c
    function getUnique(a, b, c) {
      var c = c || [];
      var ta = a.slice().sort();
      var tb = b.slice().sort();
      var x, y, found = false;
      for (var i=0, iLen=ta.length; i

    But your comment on the first answer indicates that you want the elements that are common to both arrays, which is simpler:

    function getCommon(a, b) {
      var c = [];
      var ta = a.slice().sort();
      var tb = b.slice().sort();
      var t, found;
    
      for (var i=0, iLen=ta.length; i

    You need to work out what to do with duplicates. In the first case, a duplicates will be treated as unique if there isn't a duplicate in the other array. In the above, duplicates don't matter unless they are duplicated in both arrays.

提交回复
热议问题