SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Wizard
    Join Date
    Feb 2007
    Location
    Southern California
    Posts
    1,338
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    Comparison/sort function gives no results

    Using the book, "Professional JavaScript for Web Developers," I'm working on integrating the following sorting code, but there are no results or errors in the console:

    Code:
    function colorsCompare(value1, value2) {
    	var colors = (value1 - value2);
    	return colors;
    }
    In the body I have a div for inserting the result:
    Code:
    <div id="arrayStuff" style="padding:1em; margin: 1em;background-color: #eee; border-radius: 6px;">&nbsp;</div>
    I use this script to allow the user to add to an array called colors and show it in the above div:

    Code:
    <script>
    colors = [],
    form = document.getElementById('formColor');
    (function sampleArray() {
    	"use strict";
    
    	form.addEventListener("submit", function(e) {
    	    e.preventDefault(); // prevents the form from submitting
    		var newColor = formColor.newColorInput.value;
    		colors.push(newColor);
    			fillArrayStuff();
    	}, false);
    })();
    
    </script>
    On clicking the Go button, these functions get called, and they are supposed to sort numbers into natural sort order:

    Code:
    function fillArrayStuff() {
    	document.getElementById('arrayStuff').innerHTML = "Array: " + colors.join(', ');
    }
    
    function colorsCompare(value1, value2) {
    	var colors = (value1 - value2);
    	return colors;
    	fillArrayStuff();
    	// not working
    }
    
    
    <button onClick="colorsCompare();">Sort numerical array order</button>
    I am successfully able to remove the first array item, reverse the array order, sort the array order digitally, and give an alert for which numbers are higher than 20. But this code I haven't gotten to work. The book is pretty sparse usage with regards to user-generated content. What is missing from the code?
    Steve Husting

  2. #2
    SitePoint Wizard
    Join Date
    Feb 2007
    Location
    Southern California
    Posts
    1,338
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Found an answer that works. Replace the above function colorsCompare with this:

    Code:
    function colorsCompare() { "use strict";
        var item = colors.sort(function(a,b) { return parseFloat(a) - parseFloat(b) } );
        fillArrayStuff();
    }
    Steve Husting


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
  •