CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   JavaScript programming (http://www.codingforums.com/forumdisplay.php?f=2)
-   -   Resolved sorting through objects in an array (http://www.codingforums.com/showthread.php?t=288426)

JonBMN 02-28-2013 02:37 AM

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;
        }
}


jmrker 02-28-2013 05:07 AM

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>


felgall 02-28-2013 06:04 AM

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.

Airblader 02-28-2013 08:59 AM

@ 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 );


Logic Ali 02-28-2013 10:30 AM

Quote:

Originally Posted by JonBMN (Post 1316451)
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 );


JonBMN 02-28-2013 03:34 PM

@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?

Logic Ali 02-28-2013 04:37 PM

Quote:

Originally Posted by JonBMN (Post 1316594)
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' ) );


JonBMN 02-28-2013 04:50 PM

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;
                });
        }
}


Logic Ali 02-28-2013 05:38 PM

[QUOTE=JonBMN;1316606]
Quote:

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.

JonBMN 02-28-2013 05:49 PM

what do you mean the callback function wouldn't work anyway?

rnd me 02-28-2013 05:53 PM

Quote:

Originally Posted by Airblader (Post 1316525)
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;
} );


JonBMN 02-28-2013 06:29 PM

*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));
    });


Logic Ali 02-28-2013 09:17 PM

Quote:

Originally Posted by JonBMN (Post 1316642)
*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];
    });


Airblader 02-28-2013 10:59 PM

@ 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).

rnd me 02-28-2013 11:07 PM

Quote:

Originally Posted by Airblader (Post 1316759)
@ 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.


All times are GMT +1. The time now is 09:30 PM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.