Creating array of unique values from another array
I have a form that might have 10 select boxes dynamically generated. At any point in time their values might be:
1
1
4
2
5
4
3
6
6
9
I want to produce an array of unique values contained in this list. So I want to produce a list like:
1
4
2
5
3
6
9
I guess the logic is to create the second array by looping through the first array. As I move through the first array I need to loop through the second array and test to see if the value in the first array already exists in the second array. If it does - move on, if it does not, add the value to the second array. Any ideas on the best way to do this please? Thanks for any help.
Actually I only see a need for one "global" array here.
1. Get the selection value, via onChange() event.
2. Iterate thru the array and perform an equivalency on each
element value with the selection value.
3. During the iteration, if an equivalency is found, break out
and do nothing.
4. If the iteration completes and no values were found, add the
value to the array (see note, below).
Note: You can also re-sort the array if you feel the need. This
might prove useful if you expect alot of elements, but it probably
isn't necessary.
You may also need to take into account if a selection value,
previously selected, is de-selected and the value is also in the
arry.
Try this:
This code puts a 0 in the unique values array if any of the select lists have not been changed from their default.
<HTML>
<Head>
<Script Language=JavaScript>
allValues = new Array();
uniqueValues = new Array();
function getSelection(isList){
isValue = isList.options[isList.selectedIndex].value;
if (!isValue){isValue = 0}
return isValue;
}
<script type="text/javascript">
<!--
Array.prototype.getUnique = function () {
var o = new Object();
var i, e;
for (i = 0; e = this[i]; i++) {o[e] = 1};
var a = new Array();
for (e in o) {a.push (e)};
return a;
}
alert([1,2,3,3,4,5].getUnique())
// -->
</script>
“The power of the Web is in its universality. Access by everyone regardless of disability is an essential aspect.”
—Tim Berners-Lee, W3C Director and inventor of the World Wide Web
I have entitled this 'Question for Charles' because my questions are about his code - but if anyone else can answer, I would be very grateful to be enlightened. Charles always seems to provide very succinct solutions - unfortunately I rarely understand them. Can anyone explain what the difference is between:
Array.prototype.getUnique = function ()
and
function getUnique()
Also, I was unde the impression that for loops went like this:
for (i=0;i<20;i++)
but Charles has used:
for (i = 0; e = this[i]; i++)
why isn't it 'i = this[i]' ?
I realise I am being thick here but would love to be put out of my thickness.
The syntax Charles used to declare the function meant that it was added to the methods of the Array object. This allows for more elegant code - you can use [1,2,3,3,4,5].getUnique() rather than getUnique([1,2,3,3,4,5]).
For loops in JavaScript are actually much more powerful than they first appear. The general syntax is this:
for ([initial-expression]; [condition]; [increment-expression]) {
While often used in the form you describe, it is perfectly possible to have any condition in the second section. In this case, it is an assignment to the variable e that returns the assigned value - so when the value of this[i] evaluates to false (i.e. the end of the array has been reached) the loop stops.
Adam
"If you’re not using valid HTML, then you haven’t created a Web page. You may have created something else, but it isn’t a Web page." - Joe Clark
Thanks Adam, nearly understand - perhaps one more push. Again, referring to Charles' code:
Array.prototype.getUnique = function () {
********This is a different way of creating a function that means it was 'added to the methods of the Array object'. Not quite sure what this means but anyway ...
var o = new Object();
******* var o is a new Array object?
var i, e;
for (i = 0; e = this[i]; i++) {o[e] = 1};
********* e = this[i] - what is 'this[i]'?
var a = new Array();
for (e in o) {a.push (e)};
******** for (e in o) - never seen this syntax before. What does it mean?
******** a.push (e) - again, never seen this syntax before. What does it mean?
return a;
}
Again, thanks for any help. I figure if I could really understand Charles' code I would take a big leap forwards. Cheers.
I don't know how coherent this will be, but here goes...
JavaScript has a number of built in objects, basically collections of data and functions ("methods") in one neat package. Some of them are used to represent data types, such as the Array object. One of these is implicity created whenever you declare an array.
Array objects come with certain built-in methods, such as pop() which removes the last element in the array and returns it. The first line of the code adds the function to all array objects, so you can use the syntax I described. Since when the function is called it is owned by an array object, you can access the array object using "this" as demonstrated.
The next line declares a new (but empty) object called o which stores nothing important, and has data added to it later. Specifically, it is turned into an array-like object whereby it has a property set to 1 for each element in the "this" array.
The alternate for loop syntax is a less common but perfectly legitimate way of looping through all the properties in an object.
push() is a standard array method which adds its argument (in this case e) to the array it is called on.
Basically, the code adds a method to all arrays, which when called does the following:
[list=1][*]Create an empty object, o.[*]Declare some variables, i and e.[*]Loop through all the elements in the array. For each one, mark it as present by setting a property of o. If any element is present twice, the count does not increase.[*]Declare a new empty array, a.[*]Loop through all the properties of o and add them to the end of a. This means a will have a list of each unique element in the original array.[*]Return a as the method's result.[/list=1]
Adam
"If you’re not using valid HTML, then you haven’t created a Web page. You may have created something else, but it isn’t a Web page." - Joe Clark
And what I like most about this code is the way it can be
implemented, as no "globals" are needed. As each selection option
is selected/deselected, the array can be re-created by iterating thru
the desired form objects and grabbing the selected options. The
values are simply passed to the proto and the results produce an
array with "non-dup" values.
This also means no maintenance is required, as with a global array,
when de-selections may occur (such as multi-selection lists).
Of course, its use can be tailored for alot of other things as well.
A real nice proto-type, compliments of Charles.
Array.prototype.getUnique = function () {
var o = new Object();
var i, e;
for (i = 0; e = this[i]; i++) {o[e] = 1};
var a = new Array();
for (e in o) {a.push (e)};
return a;
}
alert([1,2,3,3,4,5].getUnique())
returns 1,2,3,4,5,clone
Where is the "clone" value coming from and how do I get rid of it?
Bookmarks