PDA

View Full Version : another one: reiterating thru various arrays, only "CONCAT" nonrepeats!!


BrightNail
11-26-2002, 04:18 PM
hey all,

again it is me...sorry for sooo many questions...many times, I am looking for advice on streamlining my existing code or giving me ideas..

I need to concat some arrays,,BUT many of them will have some items that are ALSO in the others...is there a built in function of javascript or a clever way to compare two arrays, then concat what AND NOT HAVE REPEATS>>>. for instance.

var firstArray = ('joe','tim','linda','jane','max','james')
var secArray = ('sam','pete','tim','larry')

as you can see, there are TWO "tim".. one in each array.. I want to concat each of these, but only display "tim" once.

so the new array would be:
('joe','tim','linda','jane','max','james','sam','pete','larry')

maybe do a Math.max and get the greater array length..then do a for loop thru it and compare the values with the second array,,,if any match, throw it out...???

beetle
11-26-2002, 04:59 PM
Sure!<html>
<head>
<title>Array Merging</title>
<script type="text/javascript">

function Array.prototype.merge() {
var a = this;
var b;
for (var i=0; i<arguments.length; i++) {
b = arguments[i];
for (var j=0; j<b.length; j++)
if (!a.findVal(b[j])) a.push(b[j]);
}
return a;
}

function Array.prototype.findVal(val) {
for (var i=0; i<this.length; i++)
if (this[i] == val) return 1;
return 0;
}

// Prototype push() for browsers that don't have it
function Array.prototype.push(val) {
this[this.length] = val;
}

</script>
</head>
<body>
<script type="text/javascript">

var firstArray = ['joe','tim','linda','jane','max','james'] ;
var secArray = ['sam','pete','tim','larry'];

var finalArray = firstArray.merge(secArray);
alert(finalArray);

// Example using multiple arrays

var colors1 = ['red','orange'];
var colors2 = ['orange','yellow'];
var colors3 = ['yellow','green'];
var colors4 = ['green','blue'];
var colors5 = ['blue','indigo'];
var colors6 = ['indigo','violet'];
var colors7 = ['violet','red'];
var colors = colors1.merge(colors2, colors3, colors4, colors5, colors6, colors7);
alert(colors);
</script>
</body>
</html>

BrightNail
11-26-2002, 05:10 PM
holdon..

did you just code this morniing??? hahahhahha, that is some fancy stuff..

I have a question for you..

why did you use "Array.prototype" before your function names,,,why not just use the function name without that reference????

also, I didn't see an object created..I thought you could only prototype objects ??

james

beetle
11-26-2002, 06:44 PM
Ya, only took a few minutes ;)

You can prototype datatypes too

String
Number
Array
Boolean

Like a (useless) method to get the reciprocal of a number

function Number.prototype.recip() {
return 1/this;
}

var myNum = 3;
var myRecip = myNum.recip();

beetle
11-26-2002, 06:57 PM
Oh, and you'll probably like some of the stuff I've done with array sorting and such...<html>
<head>
<title>Virtual DB test</title>
<style>
table.dvdList {
font: .8em Verdana, sans-serif;
border-collapse: collapse;
width: 100%;
}
table.dvdList th {
background-color: #EEE;
border: 1px solid #666;
padding: 5px;
}
table.dvdList td {
border: 1px solid #666;
padding: 3px;
}
table.dvdList caption {
font: 1.5em 'Trebuchet MS',Verdana, sans-serif;
}
table.dvdList caption em {
font-size: .8em;
}
div.example {
color: red;
font: 1em 'Courier New', mono;
}
</style>
<script type="text/javascript">

function dvdlist(listName) {
this.listname = listName;
this.format = new Array("Title","Actor","Director","Company","Length","Year","Format","Genre","Comments");
this.list = new Array();
var i = 0;
this.list[i++] = new dvd("Cadence","Charlie Sheen, Martin Sheen","Martin Sheen","Movie Group","97 mins",1990,"NTSC","Action/Adventure","Dad and son in Army jail drama");
this.list[i++] = new dvd("Conspiracy Theory","Mel Gibson, Julia Roberts","Richard Donner","Warner Bros","130 mins",1997,"PAL","Thriller","Taxi driver with a past");
this.list[i++] = new dvd("Devils Advocate","Keanu Reaves, Al Pacino","Taylor Hackford","Twentieth Century Fox","138 mins",1997,"PAL","Thriller","Legal/Satan twist");
this.list[i++] = new dvd("Gladiator","Russell Crowe","Ridley Scott","Dreamworks Pictures","149 mins",2000,"PAL","Action/Adventure","Set in Ancient Rome");
this.list[i++] = new dvd("House II","Ayre Gross","Ethan Wiley","Digital Entertainment Ltd","88 mins",1987,"PAL","Horror","Gramps is cool!");
this.list[i++] = new dvd("Lost Boys","Jason Patric, Keifer Sutherland","Joel Shumacher","Warner Bros","93 mins",1987,"PAL","Thriller","Vampire film with a twist");
this.list[i++] = new dvd("True Lies","Arnold Swarzenegger","James Cameron","Warner Bros","135 mins",1994,"PAL","Action/Adventure","Spy action");
this.list[i++] = new dvd("Wyrd Sisters","Various (Animation)","Jean Flynn","Various","140 mins",2000,"PAL","Sci-Fi/Fantasy","Animation of Terry Pratchett book");
this.list[i++] = new dvd("Fistful of Dollars","Clint Eastwood","Sergio Leone","United Artists/MGM","97 mins",1964,"PAL","Western","Spaghetti Western");
this.list[i++] = new dvd("Few Dollars More","Clint Eastwood","Sergio Leone","United Artists/MGM","126 mins",1965,"PAL","Western","Spaghetti Western");
this.list[i++] = new dvd("The Good The Bad The Ugly","Clint Eastwood","Sergio Leone","United Artists/MGM","154 mins",1966,"PAL","Western","Spaghetti Western");
this.list[i++] = new dvd("Eraser","Arnold Swarzenegger","Charles Russell","Warner Bros","107 mins",1996,"PAL","Action/Adventure","Witness Protection type");
this.list[i++] = new dvd("6th Day","Arnold Swarzenegger","Roger Spottiswoode","Columbia Pictures","124 mins",2000,"PAL","Sci-Fi/Fantasy","Arnie clone takes over his life");
this.list[i++] = new dvd("Matrix","Keanu Reaves","The Wachowski Bros","Warner Bros","135 mins",1999,"PAL","Sci-Fi/Fantasy","Sci-Fi with excellent graphics");
this.list[i++] = new dvd("End of Days","Arnold Swarzenegger","Peter Hyams","Universal","121 mins",1999,"PAL","Action/Adventure","Fight the devil");
this.quantity = i;
this.error = "Title Not Found";
}

function dvd(title, actor, director, company, length, year, format, genre, comments){
this.title = title;
this.actor = actor;
this.director = director;
this.company = company;
this.length = length;
this.year = year;
this.format = format;
this.genre = genre;
this.comments = comments;
this.selected = true;
}

function dvdlist.prototype.display(qty) {
var shown = 0;
if (typeof qty == 'undefined') var qty = this.quantity;
document.write('<table class="dvdList"><tr>');
for (var i=0; i<this.format.length; i++)
document.write('<th>'+this.format[i]+'</th>');
document.write('</tr>');
for (i=0; i<this.quantity; i++) {
if (this.list[i].selected && shown++ < qty) {
document.write('<tr>');
for (var j in this.list[i]) {
if (j != 'selected') {
var t = eval('this.list['+i+'].'+j);
document.write('<td>'+t+'</td>');
}
}
document.write('</tr>');
}
}
document.write('<caption>'+this.listname+'</caption>');
document.write('</table>');
}

function dvdlist.prototype.select(field, val) {
var r = new RegExp(val,"i");
for (var i=0; i<this.quantity; i++) {
var t = eval('this.list[i].'+field);
if (!r.test(t)) this.list[i].selected = false;
}
}

function dvdlist.prototype.selectAll() {
for (var i=0; i<this.quantity; i++) {
this.list[i].selected = true;
}
}

function dvdlist.prototype.sortBy(field) {
this.list.sort(sortHandler);

function sortHandler(a, b) {
var aa = eval('a.'+field);
var bb = eval('b.'+field);
if (aa == bb) return 0;
return (aa > bb) ? 1 : -1;
}
}

function dvdlist.prototype.get(field, val) {
for (var i=0; i<this.quantity; i++) {
var t = eval('this.list[i].'+field);
if (t == val) return this.list[i];
}
return this.error;
}



</script>

</head>
<body>
<script>
var myList = new dvdlist("My DVDs");
document.write('<br /><div class="example">Example of full list, unchanged</div>');
myList.display();

document.write('<br /><div class="example">Example of limiting results to 5</div>');
myList.display(5);

document.write('<br /><div class="example">Example of limiting results to 5 and sorting by "year"</div>');
myList.sortBy('year');
myList.display(5);

document.write('<br /><div class="example">Example of sorting by "year" where "actor" contians "arnold"</div>');
myList.sortBy('year');
myList.select('actor','arnold');
myList.display();

document.write('<br /><div class="example">Example of sorting by "title" where "genre" is Action/Adventure</div>');
myList.selectAll();
myList.sortBy('title');
myList.select('genre','action');
myList.display();

document.write('<br /><div class="example">Example where "genre" is Action/Adventure and "company" is "Warner Bros"</div>');
myList.selectAll();
myList.select('genre','action');
myList.select('company','warner');
myList.display();
</script>
</body>
</html>

BrightNail
11-27-2002, 06:29 PM
hey beetle,

I sent you a message..check it when you get a chance..

thanks --> james

beetle
11-27-2002, 08:47 PM
Whew. :eek: You really fried my noggin with this one. Do it again and my brain will be like tapioca!

Just kidding :D

Well, here it is (I hope)

http://www.lanwizards.com/test4.htm

If I've ever done anything that showcases the benefits of OO in javascript, this has to be it :D

BrightNail
11-27-2002, 09:13 PM
hey,

oh sh$T !!!!!!!!!!!

that is some good code: I just tried this in:
IE on PC --> GOOD
Netscape on PC --> errors (see below)
Mozilla on linux -->errors (see below)

Error: missing ( before formal parameters
Source File: http://www.lanwizards.com/test4.htm
Line: 29, Column: 14
Source Code:
function Array.prototype.merge() {


not sure what that means?? I looked at the code, and couldn't understand why the error other than maybe Mozilla 0.9 and Netscape doesn't understand OO js??? any ideas...

I'm still scratching my head on that code..hahahahahahaha

beetle
11-27-2002, 09:47 PM
Nah, they just apparently prefer the other style of declaration for methods. I switched them all over. Worked for me on Mozilla.

So it does what it's supposed to? I was pretty sure, but not 100%

Oh, and if this works in NS4, I'd be surprised as hell.

BrightNail
11-27-2002, 10:16 PM
dude!!!!

yeah, it works in mozilla now.

I'll have to customize it, but I think it is doing what it needs..to..

I'll have to dig deeper and see exactly what you are doing...trust me, its not an easy task, your code is very complex..so I'll reread it and determine what exactly is going on and then let you know..I think though, it is near perfect....

I am curious as to 'why' you are passing the "numbers" when you also pass the "searchterm"...

actuall, I just looked thru it and compared things and it looks really really nice...

I'm gonna study this thing.....I'm rather shocked you busted this out sooo soooooonnnnnnn

james

beetle
11-27-2002, 10:25 PM
Perhaps when I have more time I can educate you :D

BrightNail
11-28-2002, 01:14 AM
hey,

-->actually, I see the issue.. you are returning everything to me as groups of strings rather than
groups of arrays... I tried doing this:

Array.prototype.dump = function() {
var a = new Array();
for (var i=0; i<this.length; i++) {
a += new Array (this[i]);
}
alert(a);
}

but that didn't work-->
I guess the question is given a string of data, how do you turn it into an array so that the values which are seperated by a comma are array values.

even though you are returning values in the proper goups, they are groupsof strings..so there is no way to seperate them - rather than array indexes/values.

I guess I could "split" the strings in each grouping on the "comma" and then assign those values into the dropdowns??? what do you think, doable/

************************************
everythign looks good on my end in that I integrated it within my code..

my only question is that you have an alert returning the "results"..

how can I return it having the format like so - the reason being is that the result I funnel to a function which parses the data and sends that data to the appropriate function..ala...

function filldrops(plate){
populatePrice(plate);
populateName(plate);
populateCar(plate);
populateColor(plate);
}

so based on your code..how can I have the result of "a" which you alert....represent this data structure...

var a = new Array(
new Array(new Array(10),new Array(20))
new Array('bob','mary','john')
new Array('saturn','dodge','lincoln')
new Array('red')

);

your code is checking just perfectly and returning the data that shows all matches and omissions are corrrect...

My only question is...how can I return the data to represt that above....basically, the prices are multi-dimensional within the 'a' array, while all other data is only 2d dimenionsal....if the array is empty, it still is placed, but of course, is empty.

the reason for the prices being seperated like this is because there can be a few price dropdowns, so I need a way to reiterate over the "0" index of the "a" array to pass that data to the appropriate dropdowns...(price)...

james

************************************

beetle
11-28-2002, 03:45 AM
No no no no.....

The dump() method is just a textual output for the array data. I used it for debugging and for the example's display, it's not really something you'd use in your application.

The data returned by the method mergeOnValue() IS the array you want, with only 1 caveat: The prices aren't arrays as you'd like them...

So, in my example, maryArray looks like this

maryArray == [
[10,20,30],
['max','mary','joe','peter'],
['saturn','toyota','VW','Dodge','lincoln'],
['brown','silver','red']
]

and NOT

maryArray == [
[[10],[20],[30]], <-- Difference is here
['max','mary','joe','peter'],
['saturn','toyota','VW','Dodge','lincoln'],
['brown','silver','red']
]

However, I'm sure it can be modified to do so....but it might be easier to store prices as a character-separated string, and split/parse them later.

To answer your earlier question about passing the number along to the mergeOnValue() method. That number is the index in the 2nd dimension of each 'show' array in which the method should check for the search string. I could have it iterate through each array in the 1st dimension to find the value, but since we are working with a set data format, I saw no need to take that extra processing step.

BrightNail
11-28-2002, 04:42 AM
hahahahahha,

you know something...I WAS looking at that dump and thinking...is this really needed.........but I was at work and didn't have time to go over everything in your code...

how funny...

yeah, I already thought of some ways I could parse the prices etc....