Sorting arrays within an array by a value - javascript

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

Related

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.

Sort JavaScript array with mixed characters

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.

Do I need parseInt if I want to sort numeric object keys?

I need to sort object keys as integers, they are all known to be integers for sure. (Set with a number variable like in the example).
This is not really a problem, I am just curious.
var steps = {}
steps[1] = true
steps[9] = true
steps[3+2] = true
steps[40] = true
var unsorted = Object.keys(steps), sorted = unsorted
.map(function(a){ return parseInt(a) })
.sort(function(a, b){ return a - b })
console.log(sorted)
Above, do I need that line with map and parseInt? If I comment out the line, everything seems to be OK. But I am unsure. Are there circumstances where usage of parseInt can make difference?
No you don't need to parse keys to numbers explicetely since substraction operator does it for you anyway. From the spec:
...
5. Let lnum be ToNumber(lval).
6. Let rnum be ToNumber(rval).
so both operands are converted to Number type.
Your code can be
var unsorted = Object.keys(steps),
sorted = unsorted.sort(function(a, b) { return a - b; });
It's okay to do the following :)
.sort((a, b) => parseInt(a) - parseInt(b))

Why is the sorting of this object array failing?

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;

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