Why is the sorting of this object array failing? - javascript

I'm trying to sort this object by the score value so I can populate a highscores table. Found this method of sorting which works lovely for sorting smallest to highest with a - in the formula, but when I try and reverse it with a + it doesn't work. I'm confused..
JS:
scores = [
{"n":"Arne", "score":700},
{"n":"Bertil", "score":430},
{"n":"Carl", "score":901},
{"n":"David", "score":30},
{"n":"Eric", "score":23},
{"n":"Frida", "score":118},
{"n":"Greg", "score":221},
{"n":"Hulk", "score":543}
];
scores.sort(function(a, b) {
return a.score + b.score;
});
//add rows to table from scores object
var t = document.getElementById('table');
for (var j in scores) {
var r = document.createElement('tr')
r.innerHTML = '<td><span></span></td><td>'+scores[j].n+'</td><td>'+scores[j].s+'</td>'
t.appendChild(r);
}

You mention that you're trying to reverse the sort, which originally involved subtraction.
Thus I think it's fair to assume that your original sort was like this...
scores.sort(function(a, b) {
return a.score - b.score;
});
If you want to sort in the opposite direction, simply reverse the order of the subtraction:
scores.sort(function(a, b) {
return b.score - a.score;
});

your sort function should return positive , 0 , or negative values
you probably trying to add some numbers there which is a mistake.
try here :
http://jsbin.com/icojaz/edit#javascript,html
it sorts by score.

According to http://www.w3schools.com/jsref/jsref_sort.asp you can see that you just reverse the input parameters like this: return a.score - b.score;

Related

Sort an object array by euclidean distance

I'm trying to sorte an object array by distance. Each object has a x and y coordinate and I want to sort the array so I have the next index is the closest point to index - 1
To do that, I created the following functions:
function compare(a, b) {
dist_yy = (b.bounds.y) - (a.bounds.y);
dist_xx = (b.bounds.x) - (a.bounds.x);
dist = Math.sqrt(dist_yy*dist_yy + dist_xx*dist_xx);
console.log("distance " + dist)
return dist;
}
function sort_overlays(currOverlays) {
sorted_overlays = currOverlays.sort(compare);
currOverlays.forEach(element => {
console.log(element);
});
return sort_overlays;
}
However, it does not seem to work, since I was inspecting the final array (with 700+ points) and some look out of order.
Am I applying the compare function correctly?
kind regards
No, you are not applying your compare function appropriately. A comparer function f(a,b) is meant to return:
A negative number: sort a to an index lower than b
Zero: don't sort
A positive number: sort a to an index higher than b
You are returning a distance, which is meaningless from a comparer perspective.
Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Sorting arrays within an array by a value

I have a single array looking like this:
var x = [[29,"Abc","9320","390"],[932,"123","9301","9032"], ...]
I'm looking to sort this array, so that it is organised by the first value of each array. In this case, that would look like this:
[[932,"123","9301","9032"], [29,"Abc","9320","390"], ...]
I've attempted to use .forEach but have been unable to get it working. Could anyone offer any suggestions?
Try this:
var x = [[29,"Abc","9320","390"], [932,"123","9301","9032"]];
var sorted = x.sort(function(a, b) {
return b[0] - a[0];
});
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
The proper way to do with sort is this:
var sorted = x.sort(function(a, b) {
return a[0] - b[0];
}).reverse(); // the sort is in ascending order so we need to finally reverse the array to have your final array in descending order!
or even better:
var sorted = x.sort(function(a, b) {
return b[0] - a[0];
})
if you compare the values using a < or > it wont always work:
Sorting in JavaScript: Shouldn't returning a boolean be enough for a comparison function?
However for numbers using a '-' is fine:
How to sort an array of integers correctly

Sort an array in specific order javascript

I have an array like this
arr1 = ["P2.13","P1.13","P4.13","P3.13", "P2.14","P2.14","P1.14","P4.14","P1.15","P2.15","P3.15","P4.15"];
How can I sort the array by the number after the dot FIRST, from 13 to 15, then sort by the number after "P" from 1 to 4? Finaly I want an array like this
arr2 = ["P1.13","P2.13","P3.13","P4.13","P1.14","P2.14","P3.14","P4.14","P1.15","P2.15","P3.15","P4.15"];
Appreciate!!
Pass a function into sort. The following will work for the precise test case provided, but would need to be modified if the input is more general.
arr1.sort(function(a, b) {
return a.slice(-2) - b.slice(-2) || a[1] - b[1];
});
Note that this will mutate arr1.
For programs that include many functional programming I choose Underscore library.
You can directly call sortBy function based on multiple attributes with a hacky trick by joining them. Here is the code:
var sortedArray = _.sortBy(arr1, function(item) {
var nums = item.split('.');
return [nums[1], nums[0]].join("_");
});
However, you can still use Javascript sort function to sort list with customized compare function. Here is the code:
arr1.sort(function(x, y) {
var numsX = x.split('.');
var numsY = y.split('.');
if (numsX[1] !== numsY[1]) {
return compare(numsX[1], numsY[1]); // compare the number after dot first
}
return compare(numsX[0], numsY[0]); // compare the number before dot after
});
// General comparison function for convenience
function compare(x, y) {
if (x === y) {
return 0;
}
return x > y ? 1 : -1;
}
Check two examples on fiddle
Underscore sort vs
Javscript sort
This is my new account, I don't have reputation to post more than 2 links. You can search underscore library.
Thanks.

JavaScript: Find object with Highest & Lowest

This seemed pretty straight forward,so I was surprised when it did not work. I am trying to find the object with the highest and lowest 'price'. First, please confirm or correct my logic. If, the logic is correct, then please suggest what might be the problem.
var high;
var low;
var j=0;
for (i in obj) {
//alert(obj[i].price);
if(j===0){
high=obj[i].price; low=obj[i].price
}else{
if(obj[i].price > high){high=obj[i].price}
if(obj[i].price < low ){low =obj[i].price}
}
alert("high: " + high +", low: " +low);
j++;
}
Note: This works fine: for (i in obj) { There is another portion of the script that cycles through the list perfectly and with this methodology.
Math.max and Math.min are built-in methods that can be used to find the highest or lowest numbers from the arguments passed. One technique that you can use with these functions is applying them to an array of numbers.
What you have should perform just fine, but if you're looking for something more concise, here's an example of the technique:
var arr = [],
high, low;
for (var i in obj)
arr.push(obj[i].price);
high = Math.max.apply(Math, arr);
low = Math.min.apply(Math, arr);
Example: http://jsfiddle.net/cCexG/
You may also want to add a hasOwnProperty() check to prevent from iterating over enumerable inherited properties. This could possibly be the cause of your current problem, either that or the missing var keyword for the i variable.
for (var i in obj) {
if (obj.hasOwnProperty(i) && obj[i].price)
arr.push(obj[i].price);
}
You can simply sort the array of objects by price in this way:
objects.sort(function(a, b) {
return a.price < b.price ? -1 : 1
});
the code above will sort objects by brice ascending (replace "<" with ">" for descending order)... then you can access the lowest with: objects[0] and the highest with: objects[objects.length-1]
Edit: is working now. I was just going to point out the Math.min() and max but someone beat me to it ;)!
var prices = ["110.5", "110", "350", "255.13", "350.5", "256"];
document.writeln(prices.sort(sortASC));
document.writeln(prices.sort(sortDESC));
function sortASC(a,b){
return parseFloat(a) - parseFloat(b);
}
function sortDESC(a,b){
return parseFloat(b) - parseFloat(a);
}
http://jsfiddle.net/9BSeF/

How to sort an array of hashmaps in javascript

I have a small question regarding the sorting of a JavaScript array.
I have an array which holds basically a hashmap:
dataOfTheUserArray=new Array(6);, which is basically an array of hashmaps.
The map looks like the following:
keys: values
Symbol xyz
NumberOfStocks 1o
Price 200
So the array basically contains a map for each symbol.
Now I want to sort the array based on the price of the stock .
So what I did was:
dataOfTheUserArray.sort(sortByPriceBought);
//The call back function is
function sortByPriceBought(a, b) {
var x = a.Price;
var y = b.Price;
return ((x >y) ? -1 : ((x < y) ? 1 : 0));
}
After sorting it when I iterate through the array the highest price is in the first and all the rest is not sorted.
Is there something I am doing wrong?
I would really appreciate if someone can explain if anything went wrong in the code.
If property, a.Price is a string object, the ordering is made lexically.
Changing the code as follows may solve your problem:
var x = parseInt(a.Price);
var y = parseInt(b.Price);
You can simplify your sorting function using - instead of conditions:
function sortByPriceBought(a, b) {
return b.Price - a.Price;
}
Make sure, than all elements of array have Price property.

Categories

Resources