www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 16
  1. #1
    Join Date
    Jan 2003
    Posts
    628

    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.

  2. #2
    Join Date
    Jun 2003
    Location
    Virginia
    Posts
    675
    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.

  3. #3
    Join Date
    Jan 2003
    Posts
    628
    Thanks for your answer.
    Can you tell me how to perform an 'equivalency on each element value' please. Thanks again.

  4. #4
    Join Date
    Sep 2004
    Location
    Midwest
    Posts
    1,629
    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;
    }

    function getUnique(isForm){

    n = 0;
    uniqueValues.length = 0;
    nElements = isForm.length;
    for (i=0; i<nElements; i++)
    {
    tmpType = isForm[i].type.match('select');
    if (tmpType == 'select')
    {
    allValues[n++] = getSelection(isForm[i]);
    }
    }
    allValues = allValues.sort();
    idx = 0;
    prevValue = allValues[0];
    currValue = allValues[0];
    for (i=0; i<allValues.length; i++)
    {
    currValue = allValues[i];
    if (currValue != prevValue){idx++}
    uniqueValues[idx] = currValue;
    prevValue = currValue;
    }
    alert(uniqueValues);
    }

    </Script>
    </Head>
    <Body>
    <center>
    <br>
    <h4>Creating a Unique Value(s) Array</h4>
    <br>
    <form name=thisGroup>
    <select>
    <option selected> Make a selection </option>
    <option value=1> Lead </option>
    <option value=2> Iron </option>
    <option value=3> Copper </option>
    </select>
    &nbsp;
    <select>
    <option selected> Make a selection </option>
    <option value=1> Platinum </option>
    <option value=2> Gold </option>
    <option value=3> Silver </option>
    </select>
    <select>
    <option selected> Make a selection </option>
    <option value=1> Brass </option>
    <option value=2> Tin </option>
    </select>
    &nbsp;
    <select>
    <option selected> Make a selection </option>
    <option value=1> Earth </option>
    <option value=2> Wind </option>
    <option value=3> Fire </option>
    <option value=4> Water </option>
    </select>
    </form>
    <br>
    <input type=button value="Get Unique Value(s)" onClick="getUnique(thisGroup)">
    </center>
    </Body>
    </HTML>
    Last edited by Warren86; 09-22-2004 at 03:42 PM.

  5. #5
    Join Date
    Nov 2002
    Location
    Baltimore, Maryland
    Posts
    12,257
    <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

  6. #6
    Join Date
    Jun 2003
    Location
    Virginia
    Posts
    675
    The power of the Web is in Charles.

  7. #7
    Join Date
    Dec 2003
    Location
    Bucharest, ROMANIA
    Posts
    15,427
    Or:
    PHP Code:
    <script language="JavaScript" type="text/JavaScript">
    oldarr= new Array(1,1,4,2,5,4,3,6,6,9);
    oldarr.sort();j=0;
    newarr= new Array()
    for(var 
    i=0;i<oldarr.length;i++){
    newarr[j]=oldarr[i];j++;
        if((
    i>0)&&(oldarr[i]==oldarr[i-1])){
        
    newarr.pop();j--
        }
    }
    onload=function(){alert(newarr)}
    </script> 

  8. #8
    Join Date
    Jan 2003
    Posts
    628
    Thanks very much for all your answers.

  9. #9
    Join Date
    Jan 2003
    Posts
    628

    Question for Charles

    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.

  10. #10
    Join Date
    Nov 2002
    Location
    Dartmoor [Holiday]
    Posts
    2,382
    If I can seek to interpret:

    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

    Do something amazing (USA) | Make Poverty History

  11. #11
    Join Date
    Jan 2003
    Posts
    628
    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.

  12. #12
    Join Date
    Nov 2002
    Location
    Dartmoor [Holiday]
    Posts
    2,382
    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

    Do something amazing (USA) | Make Poverty History

  13. #13
    Join Date
    Jan 2003
    Posts
    628
    Thanks Adam, comprehension begins to dawn.

  14. #14
    Join Date
    Jun 2003
    Location
    Virginia
    Posts
    675
    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.

  15. #15
    Join Date
    Feb 2005
    Posts
    13

    Question "clone" appears in unique array

    Using Charles's syntax:

    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?

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles