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.
Related
I am trying to sort an array which contains arrays of
two elements of the form [[string, object], [string, object], ...]. Each object has a property named: currentStatusTimestamp. I am trying to sort the internal arrays based on this property. It seems that all the elements are sorted correctly except one element which stays always at the first position of the array.
You can view an example describing the problem below.
Unsorted:
Unsorted array
Sorted:
Sorted array
The first element at each line of the images corresponds to arr[0] (string) and the second to the arr[1].currentStatusTimestamp.
I have tried to sort the arrays with two different functions, but neither seem to work.
You may find the two functions below:
const sortByCurrentStatusTimestamp2 = (array) => {
array.sort((a,b) => {
return (Number(a[1].currentStatusTimestamp) < Number(b[1].currentStatusTimestamp)) ? 1 : ((Number(b[1].currentStatusTimestamp) > Number(a[1].currentStatusTimestamp)) ? -1 : 0);} );}
const sortByCurrentStatusTimestamp = (array) => {
array.sort((a, b) => {
return Number(a[1].currentStatusTimestamp) < Number(b[1].currentStatusTimestamp);
});}
The code which calls the functions is displayed below:
sortByCurrentStatusTimestamp2(entriesArray);
or
sortByCurrentStatusTimestamp(entriesArray);
You may find the code used to display the output which is shown in the images, below:
for (let e of entriesArray) {
console.log(e[0],e[1].currentStatusTimestamp);}
sortByCurrentStatusTimestamp2(entriesArray);
for (let e of entriesArray) {
console.log(e[0],e[1].currentStatusTimestamp);}
The JS .sort function requires a comparator that returns a negative number, zero, or a positive number. Your second returns a boolean.
Your first function fails because you do (a < b) ? 1 : (b > a) ? -1 : 0, but the two comparisons are equivalent, i.e. you got the second comparison the wrong way around.
It normally suffices to just return the difference between the two numeric values:
.sort((a, b) => +a[1].currentStatusTimestamp - +b[1].currentStatusTimestamp);
This will give the results in ascending order. Swap a and b to reverse that.
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
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.
I am trying to sort an array of names into least to greatest order. Unfortunately JavaScript's .sort() will not work because it has underscores and letters in it.
I have this code:
var array = new Array("S1_FORM", "S2_FORM", "S3_2_FORM", "S3_FORM", "S3_3_FORM", "S4_FORM");
var SortedArray = array.sort();
This should sort it to be like:
S1_FORM, S2_FORM, S3_FORM, S3_2_FORM, S3_3_FORM, S4_FORM
Here's a jsdfiddle:
Your sort is a bit tricky since the _FORM keeps it from being just a straightforward lexicographical sort.
Try this:
var SortedArray = array.sort(function(a, b){
a = a.slice(0, -5);
b = b.slice(0, -5);
return a < b ? -1 : (a > b) ? 1 : 0;
});
I believe you want a custom sort comparison function. See this post:
How to define custom sort function in javascript?
As SHIELDHEAD suggested, you can pass a custom comparator function into Array.sort() when you want to sort by different rules than the default alphabetical/ordinal rules.
The format of the comparator function is as follows:
function(a,b){
// if a should be before b, return -1
// if b should be before a, return 1
// if they are equal, return 0
return a < b ? -1 : a > b ? 1 : 0;
}
In your case, I believe what your comparator function will need to do is grab the substring between "S" and "F" in your strings and compare those.
You can get that substring using regex: a = a.match(/(?!S)([0123456789_])+(?!F)/g);
Here's the working code:
var array = new Array("S1_FORM", "S2_FORM", "S3_2_FORM", "S3_FORM", "S3_3_FORM", "S4_FORM");
array.sort(function(a,b){
a = a.match(/(?!S)([0123456789_])+(?!F)/g);
b = b.match(/(?!S)([0123456789_])+(?!F)/g);
return a < b ? -1 : a === b ? 0 : 1;
});
document.getElementById("output").innerHTML = JSON.stringify(array);
<div id="output"/>
EDIT: Also note that the sort() function changes the original array, so you don't need to create a separate variable to store the sorted array.
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;