473,811 Members | 2,869 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

extracting differences between two arrays

How can I extract differences between two arrays using Javascript?

I hv for example, apple, orange, pear and another array with apple,
orange and I would like to get pear.

Thanks.

Jul 23 '05 #1
4 3885
Lee
ef*****@epitome .com.sg said:

How can I extract differences between two arrays using Javascript?

I hv for example, apple, orange, pear and another array with apple,
orange and I would like to get pear.


This is really more of a general programming question than javascript:

<html>
<body>
<script type="text/javascript">
function arrayDiff(a,b) {
var seen=new Object();
for (var i=0;i<a.length; i++) {
seen[a[i]]=1;
}
for (i=0;i<b.length ;i++) {
if (!seen[b[i]]) {
alert(b[i] + " is in B, but not A");
} else {
seen[b[i]]++;
}
}
for (i in seen) {
if (seen[i]==1) {
alert(i + " is in A, but not B");
}
}
}

arrayDiff(["apple","orange ","pear"],["apple","orange ","grape"]);
</script>
</body>
</html>

Jul 23 '05 #2
ef*****@epitome .com.sg wrote:
How can I extract differences between two arrays using Javascript?

I hv for example, apple, orange, pear and another array with apple,
orange and I would like to get pear.


Here's one way, with an example:

function aDiff(aRay1, aRay2) {
// initialize aResult, and seed obj, removing dups
var obj = {}, aResult = [];
for (var idx in aRay1) obj[aRay1[idx]] = 1;
// now remove elements common to both
for (idx in aRay2) if (obj[aRay2[idx]]) delete (obj[aRay2[idx]]);
// assemble the result
for (idx in obj) aResult[aResult.length] = idx;
return aResult;
}
var a1 = ['cat', 'mouse', 'dog', 'elephant'];
var a2 = ['bush', 'dog', 'fire hydrant', 'cat'];
alert (aDiff(a1, a2).join(", "));

Csaba Gabor from Vienna

Jul 23 '05 #3
"Csaba Gabor" <Cs***@z6.com > wrote in message
news:11******** **************@ g14g2000cwa.goo glegroups.com.. .
ef*****@epitome .com.sg wrote:
How can I extract differences between two arrays using Javascript?

I hv for example, apple, orange, pear and another array with apple,
orange and I would like to get pear.


Here's one way, with an example:

function aDiff(aRay1, aRay2) {
// initialize aResult, and seed obj, removing dups
var obj = {}, aResult = [];
for (var idx in aRay1) obj[aRay1[idx]] = 1;
// now remove elements common to both
for (idx in aRay2) if (obj[aRay2[idx]]) delete (obj[aRay2[idx]]);
// assemble the result
for (idx in obj) aResult[aResult.length] = idx;
return aResult;
}
var a1 = ['cat', 'mouse', 'dog', 'elephant'];
var a2 = ['bush', 'dog', 'fire hydrant', 'cat'];
alert (aDiff(a1, a2).join(", "));

Csaba Gabor from Vienna


I'm not sure what the original poster's requirements are, but your
solution fails to identify 'fire hydrant' as being different. It seems
like that is what the OP is asking for, but I wonder if he's thought
about it. And if he does want all the differences between two arrays,
how does he want to represent those differences? One huge list? Two
lists showing the elements of array 1 not in array 2 and one showing
elements in array 2 not in array 1?

function aDiff2(arr1, arr2)
{
arr1 = arr1.concat();
arr1.sort();
arr2 = arr2.concat();
arr2.sort();

var arr1Idx = 0;
var arr2Idx = 0;

while (arr1Idx < arr1.length)
{
if (arr2[arr2Idx])
{
if (arr1[arr1Idx] == arr2[arr2Idx])
{
arr1.splice(arr 1Idx, 1);
arr2.splice(arr 2Idx, 1);
}
else
{
++arr2Idx;
}
}
else
{
++arr1Idx;
}
}

return { diff1:arr1, diff2:arr2 };
}
var a1 = ['cat', 'mouse', 'dog', 'elephant'];
var a2 = ['bush', 'dog', 'fire hydrant', 'cat'];
alert(aDiff2(a1 , a2).diff1.join( ));
alert(aDiff2(a1 , a2).diff2.join( ));

My version breaks down if the array(s) contain(s) duplicate items. I
didn't have to write a general purpose function to deal with this. It
also obviously fails if one array contains "Dog" and the other contains
"dog" (although that could be solved by sorting and comparing without
regard for case).

--
Grant Wagner <gw*****@agrico reunited.com>
comp.lang.javas cript FAQ - http://jibbering.com/faq
Jul 23 '05 #4
Thanks, all the solution was valid, but I opted to use Csaba approach
simple becuase I wanted to consolidate the differences.

But in any case, I learnt all the same from all the codes.

Jul 23 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
7016
by: Paul Morrison | last post by:
Hi all, I need to come up with some differences between arrays in Java and C, I have searched Google and so far all I have found is the following: Arrays in Java are reference types with automatic allocation of memory. In C, arrays are groups of variables of the same type in adjacent memory. Allocation for dynamic arrays is handled by the programmer. This is an 8 mark question in an old exam paper, so I am assuming there are
36
5325
by: Digital Puer | last post by:
Hi, suppose I have an unsigned long long. I would like to extract the front 'n' bits of this value and convert them into an integer. For example, if I extract the first 3 bits, I would get an int between 0 and 7 (=2^3-1). Could someone please help out? I can assume the largest returned value fits in an int. Also, I'm on a big-endian PPC (AIX), in case that matters. Ideally, I'd like to implement a prototype like: int...
1
10324
by: xllx.relient.xllx | last post by:
Hi, I have two questions: 1.)Is it true that an rectangular array is really just an single dimensional array that lets itself be treated as a multi-dimensional array? For example the following declaration: int rectangular = new int;
1
3317
by: trpost | last post by:
I am looking for a way to find the differences between 2 multidimensional arrays. I have found ways to do this based on 1 key, but I want to be able to look at differences based on all keys: For example: Array 1 => array(6) {
11
12540
by: blangela | last post by:
I am teaching a C programming course to C++ programmers and want to come up with list of _KEY_ differences between the two languages. Below is a list I have come up with so far. Have I missed any? Key Differences between ANSI C and C++ 1. C is a procedural programming language (where as C++ is an Object Oriented Programming language). This means that the C programming language does not support classes and all functionality provided...
1
1952
by: rpjd | last post by:
I am completely new to this so please bear with me here. My project involves a webpage executing php scripts via an xmlhttprequest which queries a database and returns data to the webpage. This code below is working to a degree in IE7. As I have not yet parsed http.responseText, I am getting all the code in parts.php in the alert. My php script query creates two php arrays, one a single array and a two-dimensional array such as array. My...
7
1851
by: Umesh | last post by:
How can I extract common elements of two number arrays into another array? // the following doesn't work for(k=0;k<10;k++) for(l=0;l<15;l++) if(p==q) {r=p;++m;}
6
4458
by: Werner | last post by:
Hi, I try to read (and extract) some "self extracting" zipefiles on a Windows system. The standard module zipefile seems not to be able to handle this. False Is there a wrapper or has some one experience with other libaries to
5
3650
by: Mukesh | last post by:
Hi, I am using framework 2.0. I am writing a foreach loop that will extract single dimensional arrays out of double dimensional array. I am trying writing something like this. string strDetails foreach(string str in strDetails) { //Code comes here }
0
9722
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10644
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10379
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9200
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7664
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5690
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3863
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3015
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.