Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 30
  1. #1
    New Coder
    Join Date
    Feb 2013
    Posts
    38
    Thanks
    0
    Thanked 0 Times in 0 Posts

    sorting through objects in an array

    I'm trying to sort an array of objects with this function. objArray = [{q:2}, {q:1}, {q:3}] with a key of "q". so that it will return [{q:1}, {q:2}, {q:3}].
    heres what I've got so far, I'm not sure if my logic is the one thing thats messed up or if I'm not using the correct parameter for the .sort method. please help! please no regexp or no answers just a push in the right direction please and thank you.

    Code:
    function sortingTime(objArray, key) {
    	for (var i = 0; i < objArray.length; i++) {
    		objArray = parseFloat(objArray[i]);
    		objArray.sort(key);
    		return objArray;
    	}
    }
    Last edited by JonBMN; 02-28-2013 at 07:24 PM.

  • #2
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,076
    Thanks
    38
    Thanked 498 Times in 492 Posts

    Lightbulb

    You array initialization is incorrect.
    See the following test to demonstrate the problems and the comments about them.

    Note: This does not address the sort problem because your initial premiss is wrong.

    Code:
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8" />
    <title> Untitled </title>
    </head>
    <body>
    
    <script type="text/javascript">
    var tarr = { q:2, q:1, q:3 };
    for (var key in tarr) { alert(key+' : '+tarr[key]); }  // results in only the last entry displayed
    
    var tarr = { qa:2, qb:1, qc:3 };
    for (var key in tarr) { alert(key+' : '+tarr[key]); }  // resultes in 3 entries displayed
    
    </script>
    
    </body>
    </html>

  • #3
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,623
    Thanks
    0
    Thanked 645 Times in 635 Posts
    The other thing you need to know is that objArray.sort(key); will sort the entire array with key being the comparison function used to determine the order to sort two entries into. You need to define that function to take two parameters and return a positive or negative value based on whether the entries need to be swapped or not.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #4
    Regular Coder
    Join Date
    Jan 2013
    Location
    Germany
    Posts
    578
    Thanks
    4
    Thanked 77 Times in 77 Posts
    @ jmrker

    Maybe I'm overlooking something, but the OP wrote

    Code:
    objArray = [{q:2}, {q:1}, {q:3}]
    which is completely fine and not the same as your "tarr = { q:2, q:1, q:3 }".

    @ felgall

    Not to forget returning 0 if the elements are equal.

    @ OP

    This is how it can be done.

    Code:
    var objArray = [{q:2}, {q:1}, {q:3}];
    
    objArray.sort( function (a, b) {
        if( a.q > b.q ) {
            return 1;
        } else if( a.q < b.q ) {
            return -1;
        }
        return 0;
    } );
    
    console.log( objArray );

  • #5
    Senior Coder Logic Ali's Avatar
    Join Date
    Sep 2010
    Location
    London
    Posts
    1,028
    Thanks
    0
    Thanked 207 Times in 202 Posts
    Quote Originally Posted by JonBMN View Post
    I'm trying to sort an array of objects with this function. objArray = [{q:2}, {q:1}, {q:3}] with a key of "q". so that it will return [{q:1}, {q:2}, {q:3}].
    Code:
    objArray = [{q:2}, {q:1}, {q:3}];
    
    objArray.sort( function(a, b){ return a.q - b.q; } )
    
    console.log( objArray );

  • #6
    New Coder
    Join Date
    Feb 2013
    Posts
    38
    Thanks
    0
    Thanked 0 Times in 0 Posts
    @airblader I did something like yours, but at the same time I'm trying to pass the key parameter in the main function which is what will be sorting it by. I understand using the callback function in .sort but I get back .sort() is not a function. Any help clearing up this mystery for me?


    would I pass in the key parameter from the main function into the callback function by chance?
    Last edited by JonBMN; 02-28-2013 at 03:44 PM.

  • #7
    Senior Coder Logic Ali's Avatar
    Join Date
    Sep 2010
    Location
    London
    Posts
    1,028
    Thanks
    0
    Thanked 207 Times in 202 Posts
    Quote Originally Posted by JonBMN View Post
    I understand using the callback function in .sort but I get back .sort() is not a function.
    Then you're not calling it on an array. You'll have to show your code.

    I think you want to be able to specify the sorting key, in which case you can write a function to do it. You cant pass parameters to the callback function, that is what sort() does.
    Code:
    objArray = [ {q:2, r:6}, {q:1, r:2}, {q:3, r:-5}, {q:9.7, r:-1}, {q:-4, r:0} ];
    
    Array.prototype.sortOnKey = function( key )
    {
      this.sort( function(a, b){ return a[ key ] - b[ key ]; } );
      
      return this;
    }
    
    console.log( objArray.sortOnKey( 'q' ) );
    
    console.log( objArray.sortOnKey( 'r' ) );

  • #8
    New Coder
    Join Date
    Feb 2013
    Posts
    38
    Thanks
    0
    Thanked 0 Times in 0 Posts
    still getting .sort is not a function...

    Code:
    function sortingTime(objArray, key) {
    	for (var i = 0; i < objArray.length; i++) {
    		objArray = parseFloat(objArray[i]);
    		objArray.sort(function (key) {
    			this.sort( function(a, b) { return a[key] - b[key] } );
    			return this;
    		});
    	}
    }

  • #9
    Senior Coder Logic Ali's Avatar
    Join Date
    Sep 2010
    Location
    London
    Posts
    1,028
    Thanks
    0
    Thanked 207 Times in 202 Posts
    [QUOTE=JonBMN;1316606]
    Code:
    objArray = parseFloat(objArray[i]);
    From that point objArray is either a number or NaN, so you can't call sort on it, and your callback function couldn't work anyway.

  • #10
    New Coder
    Join Date
    Feb 2013
    Posts
    38
    Thanks
    0
    Thanked 0 Times in 0 Posts
    what do you mean the callback function wouldn't work anyway?

  • #11
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,296
    Thanks
    10
    Thanked 584 Times in 565 Posts
    Quote Originally Posted by Airblader View Post
    Not to forget returning 0 if the elements are equal.
    a few small points for completeness:

    1. if you are comparing all numbers, subtracting one from the other will return 0 on a match, so the explicit zero-compare is not needed.

    2. if your array elements are all unique strings, you don't need a zero-compare. Since string sorting is really slow, chopping off half the workload can make a big diff on how fast the sort performs.

    3. going a bit more advanced, if you have a large array with many elements but few unique values, you might want to consider caching the sort-compare result.
    i've seen this pattern take a sort from 800ms to 35ms.

    something LIKE this:
    Code:
    var cache={}
    objArray.sort( function (a, b, c) {
       a=a.q; b=b.q;
        if((c=cache[a+b])!==undefined){return c;}
        if( a > b ) {
            return cache[a+b]=1;
        } else if( a < b ) {
            return cache[a+b]=-1;
        }
        return cache[a+b]=0;
    } );
    Last edited by rnd me; 02-28-2013 at 05:56 PM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #12
    New Coder
    Join Date
    Feb 2013
    Posts
    38
    Thanks
    0
    Thanked 0 Times in 0 Posts
    *I've figured it out! thank god. but here is the solution I came too for the .sort.........
    Code:
    return objArray.sort(function(a, b) {
            var x = a[key]; var y = b[key];
            return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        });
    Last edited by JonBMN; 02-28-2013 at 07:24 PM.

  • #13
    Senior Coder Logic Ali's Avatar
    Join Date
    Sep 2010
    Location
    London
    Posts
    1,028
    Thanks
    0
    Thanked 207 Times in 202 Posts
    Quote Originally Posted by JonBMN View Post
    *I've figured it out! thank god. but here is the solution I came too for the .sort.........
    Code:
    return objArray.sort(function(a, b) {
            var x = a[key]; var y = b[key];
            return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        });
    You don't have to return 1, 0 or -1, just the difference:

    Code:
    return objArray.sort(function(a, b) 
        {
            return a[key] - b[key];
        });

  • #14
    Regular Coder
    Join Date
    Jan 2013
    Location
    Germany
    Posts
    578
    Thanks
    4
    Thanked 77 Times in 77 Posts
    @ rndme

    1. True
    2. Not entirely -- some sorting algorithms will compare an element to itself. Your sorting function should always support this case (which just using the difference does, of course).

  • #15
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,296
    Thanks
    10
    Thanked 584 Times in 565 Posts
    Quote Originally Posted by Airblader View Post
    @ rndme

    1. True
    2. Not entirely -- some sorting algorithms will compare an element to itself. Your sorting function should always support this case (which just using the difference does, of course).
    what do you mean by "some sorting algorithms"?

    im talking about

    Code:
    function srtStr(a,b){return a>b?1:-1;}
    versus
    Code:
    function srtStr(a,b){return a>b?1:(b==a?0:-1);}
    i also said "when sorting unique strings", which means that the difference is always NaN, unless you know something i don't...

    after all, if the elements are unique, it's impossible for a proper sort function to return zero.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

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