Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 02-28-2013, 02:37 AM   PM User | #1
JonBMN
New Coder

 
Join Date: Feb 2013
Posts: 37
Thanks: 0
Thanked 0 Times in 0 Posts
JonBMN is an unknown quantity at this point
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..
JonBMN is offline   Reply With Quote
Old 02-28-2013, 05:07 AM   PM User | #2
jmrker
Senior Coder

 
jmrker's Avatar
 
Join Date: Aug 2006
Location: FL
Posts: 2,765
Thanks: 29
Thanked 453 Times in 447 Posts
jmrker will become famous soon enough
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>
jmrker is offline   Reply With Quote
Old 02-28-2013, 06:04 AM   PM User | #3
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,465
Thanks: 0
Thanked 499 Times in 491 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
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/
felgall is offline   Reply With Quote
Old 02-28-2013, 08:59 AM   PM User | #4
Airblader
Regular Coder

 
Join Date: Jan 2013
Location: Germany
Posts: 368
Thanks: 3
Thanked 44 Times in 44 Posts
Airblader can only hope to improve
@ 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 );
Airblader is offline   Reply With Quote
Old 02-28-2013, 10:30 AM   PM User | #5
Logic Ali
Regular Coder

 
Logic Ali's Avatar
 
Join Date: Sep 2010
Location: London
Posts: 961
Thanks: 0
Thanked 198 Times in 193 Posts
Logic Ali will become famous soon enoughLogic Ali will become famous soon enough
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 );
Logic Ali is offline   Reply With Quote
Old 02-28-2013, 03:34 PM   PM User | #6
JonBMN
New Coder

 
Join Date: Feb 2013
Posts: 37
Thanks: 0
Thanked 0 Times in 0 Posts
JonBMN is an unknown quantity at this point
@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..
JonBMN is offline   Reply With Quote
Old 02-28-2013, 04:37 PM   PM User | #7
Logic Ali
Regular Coder

 
Logic Ali's Avatar
 
Join Date: Sep 2010
Location: London
Posts: 961
Thanks: 0
Thanked 198 Times in 193 Posts
Logic Ali will become famous soon enoughLogic Ali will become famous soon enough
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' ) );
Logic Ali is offline   Reply With Quote
Old 02-28-2013, 04:50 PM   PM User | #8
JonBMN
New Coder

 
Join Date: Feb 2013
Posts: 37
Thanks: 0
Thanked 0 Times in 0 Posts
JonBMN is an unknown quantity at this point
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;
		});
	}
}
JonBMN is offline   Reply With Quote
Old 02-28-2013, 05:38 PM   PM User | #9
Logic Ali
Regular Coder

 
Logic Ali's Avatar
 
Join Date: Sep 2010
Location: London
Posts: 961
Thanks: 0
Thanked 198 Times in 193 Posts
Logic Ali will become famous soon enoughLogic Ali will become famous soon enough
[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.
Logic Ali is offline   Reply With Quote
Old 02-28-2013, 05:49 PM   PM User | #10
JonBMN
New Coder

 
Join Date: Feb 2013
Posts: 37
Thanks: 0
Thanked 0 Times in 0 Posts
JonBMN is an unknown quantity at this point
what do you mean the callback function wouldn't work anyway?
JonBMN is offline   Reply With Quote
Old 02-28-2013, 05:53 PM   PM User | #11
rnd me
Senior Coder

 
rnd me's Avatar
 
Join Date: Jun 2007
Location: Urbana
Posts: 3,469
Thanks: 9
Thanked 466 Times in 450 Posts
rnd me is a jewel in the roughrnd me is a jewel in the roughrnd me is a jewel in the rough
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;
} );
__________________
my site (updated 5/13)
STATS (2013/5) HTML5:90.2% MOB:14% IE7:0.5% IE8:8.6% IE9:9.8% IE10:10%

Last edited by rnd me; 02-28-2013 at 05:56 PM..
rnd me is offline   Reply With Quote
Old 02-28-2013, 06:29 PM   PM User | #12
JonBMN
New Coder

 
Join Date: Feb 2013
Posts: 37
Thanks: 0
Thanked 0 Times in 0 Posts
JonBMN is an unknown quantity at this point
*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..
JonBMN is offline   Reply With Quote
Old 02-28-2013, 09:17 PM   PM User | #13
Logic Ali
Regular Coder

 
Logic Ali's Avatar
 
Join Date: Sep 2010
Location: London
Posts: 961
Thanks: 0
Thanked 198 Times in 193 Posts
Logic Ali will become famous soon enoughLogic Ali will become famous soon enough
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];
    });
Logic Ali is offline   Reply With Quote
Old 02-28-2013, 10:59 PM   PM User | #14
Airblader
Regular Coder

 
Join Date: Jan 2013
Location: Germany
Posts: 368
Thanks: 3
Thanked 44 Times in 44 Posts
Airblader can only hope to improve
@ 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).
Airblader is offline   Reply With Quote
Old 02-28-2013, 11:07 PM   PM User | #15
rnd me
Senior Coder

 
rnd me's Avatar
 
Join Date: Jun 2007
Location: Urbana
Posts: 3,469
Thanks: 9
Thanked 466 Times in 450 Posts
rnd me is a jewel in the roughrnd me is a jewel in the roughrnd me is a jewel in the rough
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 5/13)
STATS (2013/5) HTML5:90.2% MOB:14% IE7:0.5% IE8:8.6% IE9:9.8% IE10:10%
rnd me is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 01:27 PM.


Advertisement
Log in to turn off these ads.