Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 731
Abhishek B. Avatar asked May 06 '11 05:05

Abhishek B.


People also ask

How do I remove duplicates in two arrays?

Given a sorted array, the task is to remove the duplicate elements from the array. Create an auxiliary array temp[] to store unique elements. Traverse input array and one by one copy unique elements of arr[] to temp[]. Also keep track of count of unique elements.


1 Answers

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.

like image 178
alex Avatar answered Oct 20 '22 01:10

alex