How to find unique records from two different array in jquery or javascript? - 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?

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.

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.

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

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

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>

Related

Reverse a list of characters

list = [c,a,r,p,e,t]
function reverse(list) {
var i =0; j= list.length-1;
while(i < j) {
var temp = list[i];
list[i] = list[j];
list[j] = temp;
i++;
j--;
}
return list;
}
Hello everyone, I am trying to solve the problem above. It works for an array of numbers. How can I adapt it to handle a list of characters?
Arrays can be reversed by design natively without the needs of a loop:
var list = ['c','a','r','p','e','t'];
var reversedList = list.slice(0).reverse();
Check the Mozilla Developer Network: Array.prototype.reverse() and Mozilla Developer Network: Array.prototype.slice() for more infomation.
just use .reverse(); and assuming c,a,r,p,e,t is a variable then use String() if you want to sort it by letter and use Number() if sort it by number.
sort by string:
var list = [String(c),String(a),String(r),String(p),String(e),String(t)].reverse();
sort by number:
var list = [Number(c),Number(a),Number(r),Number(p),Number(e),Number(t)].reverse();
Reference: .reverse() String() Number()
Your code throws - Uncaught ReferenceError: c is not defined. As you miss to place " or ' along with character.
Change your step array declaration step :
From : list = [c,a,r,p,e,t]
To : list = ['c','a','r','p','e','t'] or list = ["c","a","r","p","e","t"]
Your working code
var list = ['c','a','r','p','e','t'];
function reverse(list) {
var i =0; j= list.length-1;
while(i < j) {
var temp = list[i];
list[i] = list[j];
list[j] = temp;
i++;
j--;
}
return list;
}
//Call the method;
reverse(list);
jsfiddle working example :
https://jsfiddle.net/m6kt3eus/1/
Other simpler way to achieve this :
The simple way to reverse the array is reverse() in javascript
Following are the example code snippet:
var list = ['c','a','r','p','e','t'];
list.reverse();
console.log(list);
arr.reverse() is used for in place reversal of the array. The first element of the array becomes the last element and vice versa.
Syntax:
arr.reverse()
Argument
This function does not take any argument.
Return value
This function returns the reference of the reversed original array.
function reverse(list) {
var list2 = [];
for (let i = 0; i < list.length; i++)
list2.unshift(list[i]);
return list2;
}
var list = ['c', 'a', 'r', 'p', 'e', 't'];
console.log(reverse(list));

immutable js flat zip two lists

If I have two immutable lists,
const a = [1,2,3];
const b = [a,b,c,d];
is there an easy way to merge/zip them to result in:
const c = [1,a,2,b,3,c,d];
Is interleave what you are looking for: https://facebook.github.io/immutable-js/docs/#/List/interleave
const a = List([1, 2, 3]);
const b = List([a, b, c, d]);
a.interleave(b)
const a = [1, 2, 3] don't make this array immutable at all. What const does is to guarantee that you're not reassigning a. Pushing or removing items to a don't constitute a reassignment.
This is a real immutable list using immutable.js:
const a = List([1, 2, 3]);
Now.. back to zip.
If you don't want another reference, you can just use a for in the smallest list and build the zip yourself. If you want a ready-made function, you might consider using Underscore's Zip, which does exactly what you want.
If you want to develop a function from scratch then you can use the code below. Basically, the function merges the two array as interleaving the two. Consider 2 arrays, array1 = [1,2,3,4] and array2 = [a,b,c,d,e,f]. Then the below code will output a new array [1,a,2,b,3,c,4,d,e,f]
var i = 0;
var j = 0;
var k = 0;
var len1 = array1.length;
var len2 = array2.length;
var flag = true;
var newArr = [];
//Merge the 2 arrays till the smaller sized array
while (i < len1 && j < len2)
{
if(flag){
newArr[k] = array1[i];
i++; k++;
flag = false;
}
else{
newArr[k] = array2[j];
j++; k++;
flag = true;
}
}
/* Copy the remaining elements of array1[], if there are any */
while (i < len1)
{
newArr[k] = array1[i];
i++;
k++;
}
/* Copy the remaining elements of array2[], if there are any */
while (j < len2)
{
newArr[k] = array2[j];
j++;
k++;
}
console.log(newArr)

Rearranging Elements For Array of Array

I am trying to rearrange elements in an array of arrays but have been unsucessful. Can anyone offer suggestions? Here are two options I have tried. I want to swap/switch places for the first and second elements.
arr1 is an array of arrays (i.e. arr[][]) so I created arr2 to be an updated arr1
var arr2 = [];
for (var n = 0; n <arr1.length; n++){
arr2[n][0] = arr1[n][1];
arr2[n][1] = arr1[n][0];
}
The other thing I tried was:
function order(arr[]){
return [arr[n][1],arr[n][0], arr[n][2], arr[n][3]];
}
var arr2 = order(arr1);
You also need to create a new array for each item:
var arr2 = [];
for(var n = 0; n < arr1.length; n++) {
arr2[n] = [arr1[n][1], arr1[n][0]];
}
it's quite easy:
var a = arr1[n][0];
arr2[n][0] = arr1[n][1];
arr2[n][1] = a;
you need to save the first value as a variable, because if you do as you did(arr2[n][0] = arr1[n][1];), your two array indexes will have the same value.
You did:
a = 1, b = 2;
a = b;
b = a;
Which resolves in a = 2, b = 2
Also, your code as it is now, doesn't work. You need to create a new array for the simulation of multidimensional arrays in javascript.
for(i = 0; i < (yourdesiredamountofarrays); i++)
{
yourarray[i] = new Array();
}
The first example you need to use a temporary variable for the switch:
var arr2 = [];
for (var n = 0; n <arr1.length; n++){
var tempVal = arr1[n][1];
arr2[n][1] = arr1[n][0];
arr2[n][0] = tempArr;
}
The second example, in JS the variable shouldn't have brackets next to it, as it's just a loosely typed variable name.
function order(arr){
return [arr[n][1],arr[n][0], arr[n][2], arr[n][3], arr[n][4]];
}
var arr2 = order(arr1);
Next time, before asking you should check the console. The stackoverflow wiki page on JS has lots of great resources for learning to debug JS.

How to create a multidimensional array in JavaScript?

How can I create a multidimensional array in JavaScript?
I have:
var m = 4;
for (var i = 0; i < m; i++){
groupsData.name_of_bar = [];
groupsData.name_of_bar[i]['a'] = data[i].a;
groupsData.name_of_bar[i]['ab'] = data[i].ab;
groupsData.name_of_bar[i]['de'] = data[i].de;
groupsData.name_of_bar[i]['gh'] = data[i].gh;
groupsData.name_of_bar[i]['xy'] = data[i].xy;
}
If I do:
groupsData.name_of_bar[0]
I get errors:
TypeError: Cannot read property '0' of undefined
TypeError: Cannot set property 'a' of undefined
What am I doing wrong?
JavaScript doesn't support multidimensional arrays per se. The closest you can come is to create an array where the values in it are also arrays.
// Set this **outside** the loop so you don't overwrite it each time you go around the loop
groupsData.name_of_bar = [];
for (var i = 0; i < m; i++){
// Create a new "array" each time you go around the loop
// Use objects, not arrays, when you have named properties (instead of ordered numeric ones)
groupsData.name_of_bar[i] = {};
groupsData.name_of_bar[i]['a'] = data[i].a;
groupsData.name_of_bar[i]['ab'] = data[i].ab;
groupsData.name_of_bar[i]['de'] = data[i].de;
groupsData.name_of_bar[i]['gh'] = data[i].gh;
groupsData.name_of_bar[i]['xy'] = data[i].xy;
}
Each iteration through the loop, you are doing groupsData.name_of_bar = [];. This removes whatever else is already in there and replaces it with a blank array.
Also, when you do groupsData.name_of_bar[i]['a'], you need to create groupsData.name_of_bar[i] first.
A way to do this is:
groupsData.name_of_bar = [];
var m = 4;
for (var i = 0; i < m; i++){
groupsData.name_of_bar.push({
a: data[i].a,
ab: data[i].ab,
ab: data[i].ab,
de: data[i].de,
gh: data[i].gh,
xy: data[i].xy,
});
}
Note that in JavaScript, arrays can only be numerically indexed. If you want string indexes, you need to use an object.
Also, if there are no other values in data[i], then you can simplify this even further by doing:
groupsData.name_of_bar = [];
var m = 4;
for (var i = 0; i < m; i++){
groupsData.name_of_bar.push(data[i]);
}
Heck, why not just use groupsData.name_of_bar = data; and lose the loop altogether?
The way you are declaring your objects are a little off. It looks like you are attempting to create an array of objects.
var groupsData = {name_of_bar: []},
m = 4,
i = 0;
for(; i < m; i++) {
groupsData.name_of_bar.push({
a: data[i].a,
ab: data[i].ab,
de: data[i].de,
gh: data[i].gh,
xy = data[i].xy
});
}

Remove duplicate element pairs from multidimensional array

I have an array that looks like this:
1. coordinates = [ [16.343345, 35.123523],
2. [14.325423, 34.632723],
3. [15.231512, 35.426914],
4. [16.343345, 35.123523],
5. [15.231512, 32.426914] ]
The latitude on line 5 is the same as on line 3, but they have different longitudes and are therefore not duplicates.
Both the latitude and longitude are the same on line 3 and 6, and are therefore duplicates and one should be removed.
The difficulty in this question that different arrays never compare equal even if they contain same values. Therefore direct comparison methods, like indexOf won't work.
The following pattern might be useful to solve this. Write a function (or use a built-in one) that converts arrays to scalar values and checks if these values are unique in a set.
uniq = function(items, key) {
var set = {};
return items.filter(function(item) {
var k = key ? key.apply(item) : item;
return k in set ? false : set[k] = true;
})
}
where key is a "hash" function that convert items (whatever they are) to comparable scalar values. In your particular example, it seems to be enough just to apply Array.join to arrays:
uniqueCoords = uniq(coordinates, [].join)
You can use standard javascript function splice for this.
for(var i = 0; i < coordinates.length; i++) {
for(var j = i + 1; j < coordinates.length; ) {
if(coordinates[i][0] == coordinates[j][0] && coordinates[i][1] == coordinates[j][1])
// Found the same. Remove it.
coordinates.splice(j, 1);
else
// No match. Go ahead.
j++;
}
}
However, if you have thousands of points it will work slowly, than you need to consider to sort values at first, then remove duplicates in one loop.
I rewrote the answer from thg435 (It does not allow me to post comments) and prototype it also using jQuery instead, so this will work on all browsers using it (Even IE7)
Array.prototype.uniq = function (key) {
var set = {};
return $.grep(this, function (item) {
var k = key
? key.apply(item)
: item;
return k in set
? false
: set[k] = true;
});
}
You can use it like:
arr = arr.uniq([].join);
If you are not on Safari this single liner could do the job
var arr = [[16.343345, 35.123523],
[14.325423, 34.632723],
[15.231512, 35.426914],
[16.343345, 35.123523],
[15.231512, 32.426914]],
lut = {},
red = arr.filter(a => lut[a] ? false : lut[a] = true);
document.write("<pre>" + JSON.stringify(red,null,2) + "</pre>");
It might be simpler to create another array keeping only unique coordinate pairs
var uniqueCoors = [];
var doneCoors = [];
for(var x = 0; x < coordinates.length; x++) {
var coorStr = coordinates[x].toString();
if(doneCoors.indexOf(coorStr) != -1) {
// coordinate already exist, ignore
continue;
}
doneCoors.push(coorStr);
uniqueCoors.push(coordinates[x]);
}
function sortCoordinates(arr){
var obj = {};
for(var i = 0, l = arr.length; i < l; i++){
var el = arr[i];
var lat = el[0];
var lng = el[1];
if(!obj[lat + lng]){
obj[lat + lng] = [lat, lng];
}
}
var out = [];
for(p in obj){
out.push([obj[p][0], obj[p][1]]);
}
return out;
}
I am not sure about coordinates[][] dataType. Make the comparison accordingly.
var dubJRows= new Array();
for(int i = 0; i < coordinates.length -2; i++){
for(int j = i+1; j < coordinates.length -1; j++){
if (i != j && chk_dubJRows_not_contains(j)) {
innerArray1 [1][1] = coordinates[i];
innerArray2 [1][1] = coordinates[j];
if ( innerArray1 [1][0] == innerArray2[1][0]
&& innerArray1[1][1] == innerArray2[1][1]) {
dubJRows.push(j);
}
}
}
}
//REMOVE ALL dubJRows from coordinates.

Categories