Jump to content

Recommended Posts

Ok, I have a 2-d array, and I am trying to sort it numerically by the 6th column (or array[5]). The array is something like

 

array = ("Stuff", "Something else" "other stuff", 95, 95, 100);

 

The 6th column is the percent of quotient of the 4th and 5th column times 100 (basically a percent)

 

So the sorting code I have looks like the following


function value_sort(a,b) {
	a = a[5];
	b = b[5];
	return a == b ? 0 : (a > b ? -1 : 1)
}
full_array.sort(value_sort)

 

It does sort it somewhat, but When it sorts, anything below 100% (IE 99 % 98% etc.) is sorted correctly, but 100% values are below everything but 0% values. so if the array's 6th column looks like the following

 

100

99

98

97

96

100

100

100

5

6

7

8

0

0

0

 

then the sorted array will look like:

99

98

97

96

8

7

6

5

100

100

100

100

0

0

0

 

I don't really understand why. Anyone got any ideas?

never mind, I figured it out. For those who are curious the reason goes as follows:

 

Using my method, it is sorting as a numeric string, not as a quantifiable number, and since the value "100" starts with 1, it goes below every other number except for zero. To fix this, I added a preceding "0" to any number of two digits or lower. the fixed function looks like the following:

 

function value_sort(a,b) {
	a = a[5];
	b = b[5];
	if (a.length < 3){
		pre = "0";
		a = pre + a;
	}
	if (b.length < 3){
		pre = "0";
		b = pre + b;
	}

	return a == b ? 0 : (a > b ? -1 : 1);
}

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.