By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,712 Members | 2,116 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,712 IT Pros & Developers. It's quick & easy.

javascript array headache

P: n/a
M D
How can make the following program so that
remove not matching fruits from a1 and add rest in the a2 to
a1.
answer
["Apple","Grape","Pear","Water Melon", "Straberry"];
currently i get the first 3 because concat won't alocate the new
memory space for a1[4] a1[5]

var a1 = ["Apple","Banana","Orange","Grape","Pear"];
var a2 = ["Grape","Pear","Apple","Water Melon", "Straberry"];
var found;

for( var j = 0; j < a1.length; j++ ){
found = "false";
for( var i = 0; i < a2.length; i++ ){
if( a1[ j ] == a2[i] ){
found = "true";
a2.splice(i,1);
i--;
break;
}else{

}
}

if( found == "false" ){
a1.splice(j,1);
j--;
}
}
alert( a1.length );
alert( a2.length );
a1.concat( a2 );
alert( a1.length );
for( var l = 0; l < a1.length ; l++ ){
alert( a1[l] );
}
Sep 12 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a
M D wrote:
How can make the following program so that
remove not matching fruits from a1 and add rest in the a2 to
a1.
[ snip code]
// one Conditio: no double (repeated) items inside a1 or a2
var a1 = ["Apple","Banana","Orange","Grape","Pear"]
var a2 = ["Grape","Pear","Apple","Water Melon","Straberry"]
var c = a1.concat(a2)
var fruit = new Object()
var Y = new Array()
var N = new Array()

for(var i=0; i<c.length; ++i) {
fruit[c[i]]?++fruit[c[i]]:fruit[c[i]]=1
}

for (var j in fruit) {
fruit[j]>1?Y.push(j):N.push(j)
}

alert('matching: ' + Y + '\n' + 'non matching: ' + N)

Hope this helps,

--
Bart

Sep 12 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.