6

I want to get unique values from two different arrays.

Two arrays are as below in JavaScript:

<script>
var a=new Array;
var b=new Array;
a={'a','b','c','d','e'}
b={'a','d','e','c'} 
</script>

I want output like:

new array => {'a','c','d','e'}

How can I find unique records from both arrays using JavaScript prototype function or jQuery function?

Jordan Ryan Moore
  • 6,877
  • 2
  • 26
  • 27
Abhishek B.
  • 5,112
  • 14
  • 51
  • 90

5 Answers5

8

I don't know if you have the terms correct. Unique values to me would be members which appear only once in either array. It seems you want members that are present in both arrays (common values, or intersection), based on your example.

You can use jQuery to handle this. grep() is your friend.

You could do this without jQuery, but I'm not sure if the native filter() and indexOf() methods have the best browser support.

var a = ['a', 'b', 'c', 'd', 'e'],
    b = ['a', 'd', 'e', 'c'];

var common = $.grep(a, function(element) {
    return $.inArray(element, b) !== -1;
});

console.log(common); // ["a", "c", "d", "e"]

With underscore it's easy at _.intersection(arr1, arr2).

jsFiddle.

alex
  • 479,566
  • 201
  • 878
  • 984
  • @alex Thanks for Ans, but I getting console in undefined .. in Jsfiddle example.., I used Jquery 1.3.2.min.js in my application.. Is any other way.. – Abhishek B. May 06 '11 at 05:28
  • 1
    @Abhishek That just means you don't have a console object. [Try this](http://jsfiddle.net/alexdickson/QDhFD/). – alex May 06 '11 at 05:30
  • You don't need filter() or indexOf() to use plain javascript. POJS will be much more efficient than jQuery's *grep* and *inArray* functions. – RobG May 06 '11 at 05:52
  • @RobG Obviously, but it won't be as conceptually similar to the jQuery code without them. You'd have to write your own loops, which is never as pretty. :) – alex May 06 '11 at 06:01
2

I think you really meant to write:

<script type="text/javascript">
var a = ['a','b','c','d','e'];
var b = ['a','d','e','c']; 
</script>

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<iLen; i++) {
    x = ta.shift();

    for (var j=0; j<tb.length && !found; j++) { // j.length changes each loop
      if (tb[j] == x) {
        tb.splice(j,1);  // Remove match from b
        found = true;
      }
    }
    if (!found) {
      c.push(x); // If no match found, store in result
    }
    found = false;
  }
  return c;
}
var a = ['a','b','d'];
var b = ['b','e'];

var d = getUnique(a, b);
alert(d);

var c = getUnique(b,a,d);
alert(d);

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<iLen; i++) {
    t = ta[i];
    found = false;

    for (var j=0, jLen=tb.length; j<jLen && !found; j++) {
      if (t == tb[j]) {
        c.push(tb.splice(j,1));
        found = true;
      }
    }
  }
  return c;
}

alert(getCommon(a, b));

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.

RobG
  • 142,382
  • 31
  • 172
  • 209
  • Thanks a @RobG Is it faster than grep function? How it is good than jquery function grep() – Abhishek B. May 06 '11 at 06:07
  • 1
    @Abhishek It is almost always faster to do things without a library. – alex May 06 '11 at 06:11
  • Thanks a lot @RobG, I got difference The execution time is faster than grep() it is in millisecond. – Abhishek B. May 06 '11 at 06:13
  • +1 for nice native answer. BTW, is there any reason why you wouldn't break to a label as opposed to using `found` as a flag (or have I missed something)? – alex May 06 '11 at 06:13
  • @Abhishek You shouldn't be choosing one thing over another based on a difference of a millisecond. Choose those most readable. – alex May 06 '11 at 06:19
1

Find orignal answer : JavaScript array difference

You could use a Set in this case. It is optimized for this kind of operation (union, intersection, difference).

Make sure it applies to your case, once it allows no duplicates.

var a = new JS.Set([1,2,3,4,5,6,7,8,9]);
var b = new JS.Set([2,4,6,8]);

a.intersection(b);//intersect will give you the common one
Community
  • 1
  • 1
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
1

I would like to do this operation with the help of associative array support in JavaScript.

<script>
var a=new Array;
var b=new Array;
a={'a','b','c','d','e'}
b={'a','d','e','c'} 

var uniqueArray = new Array;
var tempArray = new Array;

var j = 0;
for(var i = 0; i < a.length; i++) {
    if(!tempArray[a[i]]) {
        tempArray[a[i]] = true;
        uniqueArray[j++] = a[i];
    }
}

for(i = 0; i < b.length; i++) {
    if(!tempArray[b[i]]) {
        tempArray[b[i]] = true;
        uniqueArray[j++] = b[i];
    }
}

</script>
James Jithin
  • 10,183
  • 5
  • 36
  • 51
1

Like this:

var a=['a','b','c','d','e']; //Use brackets
var b=['a','d','e','c']

var c = a.concat(b).sort();

var uniques = {};

for(var i=0; i<c.length; i++){
   uniques[c[i]] = true;
}
var uniquesArray = [];
for(var u in uniques)
  uniquesArray.push(u)

Now uniquesArray contains only unique values. Hope this Helps

Edgar Villegas Alvarado
  • 18,204
  • 2
  • 42
  • 61
  • I like this solution for finding 'distinct' values, but to me 'unique' would mean only values that appear once in either array. But going by the sample expected output in the OP I think what is really wanted here is 'common' values, i.e., those that exist in both arrays. – nnnnnn May 06 '11 at 06:05