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.
Related
There are a lot of examples for sorting some JSON array by some property (i.e. 'title')
We are using compare function like this one:
function sortComparer(a, b) {
if (a.title == b.title)
return 0;
return a1 > b1 ? 1 : -1;
}
Problem is that Serbian Latin alphabet order looks like "A, B, C, Č, Ć, D,..."
When using sortComparer above I am getting D sorted before "Č" or "Ć".
Any idea how to sort respecting current culture language?
If the locale in your system is set correctly then you can use localeCompare method instead of greater-than operator to compare the strings - this method is locale aware.
function sortComparer(a,b){
return a.title.localeCompare(b.title)
};
For sorting an array with a custom setting do as following:
Create an array with a custom order of alphabets:
var alphabets = ["A", "B", "C", "Č", "Ć", "D","Dž","Đ","E","F","G","H","I","J","K","L","Lj","M","N","Nj","O","P","R","S", "ÛŒ","T","U","V","Z","Ž"];
Create a list of test array:
var testArrray = ["B2","D6","A1","Ć5","Č4","C3"];
Create a sort function name:
function OrderFunc(){
testArrray.sort(function (a, b) {
return CharCompare(a, b, 0);
});
}
create the CharCompare function(index: sort "AAAB" before "AAAC"):
function CharCompare(a, b, index) {
if (index == a.length || index == b.length)
return 0;
//toUpperCase: isn't case sensitive
var aChar = alphabets.indexOf(a.toUpperCase().charAt(index));
var bChar = alphabets.indexOf(b.toUpperCase().charAt(index));
if (aChar != bChar)
return aChar - bChar
else
return CharCompare(a,b,index+1)
}
Call OrderFunc for sorting the testArray(the result will be : A1,B2,C3,Č4,Ć5,D6).
Test Online
Good Luck
Use The Intl.Collator like you will get perfect sorting result
function letterSort(lang, letters) {
letters.sort(new Intl.Collator(lang).compare);
return letters;
}
console.log(letterSort('gu', ['છ','ક','ખ']));
// expected output: Array ["a", "ä", "z"]
console.log(letterSort('sv', ['a','z','ä']));
// expected output: Array ["a", "z", "ä"]
More detail you can check here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collator
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.
a=['a','b','c']
b=['a','c']
I was trying to write a function that compares these both arrays and creates a third array filling the missing array member with null. So the return value should be:
['a',null,'c']
How do I do that?
P.S. Values are always in sequential order.
I am not sharing my try here because I don't want it to be improved or criticized, I know this function is not something hard to write (but it was for me) so I just want answers from experienced people.
You can use the Array.prototype.map function to loop over the a array and replace values.
var a = ['a','b','c'];
var b = ['a','c'];
var c = a.map(function(item) {
return ~b.indexOf(item) ? item : null;
});
console.log(c);
Hint: This only works if a contains at least all of the values that b contains.
A functional, but not necessarily the most efficient, solution:
var results = a.map(function(v) {
return b.indexOf(v) !== -1 ? v : null;
});
As the values are always sequential, it may be more efficient to loop with an index in each array, moving the index forward through b only when a match is found. Whether you actually want to do this as an optimisation depends on how big your arrays are.
Please try the following code,
var result = [];
a.forEach(function(item){
result.push(b.indexOf(item) < 0 ? null : item);
})
A slightly different approach without lookup with indexOf.
var a = ['a', 'b', 'a'],
b = ['a', 'b'],
c = a.map(function () {
var offset = 0;
return function (el, i) {
if (el === b[offset + i]) {
return el;
}
offset--;
return null;
}
}());
document.write('<pre>' + JSON.stringify(c, 0, 4) + '</pre>');
There are a lot of examples for sorting some JSON array by some property (i.e. 'title')
We are using compare function like this one:
function sortComparer(a, b) {
if (a.title == b.title)
return 0;
return a1 > b1 ? 1 : -1;
}
Problem is that Serbian Latin alphabet order looks like "A, B, C, Č, Ć, D,..."
When using sortComparer above I am getting D sorted before "Č" or "Ć".
Any idea how to sort respecting current culture language?
If the locale in your system is set correctly then you can use localeCompare method instead of greater-than operator to compare the strings - this method is locale aware.
function sortComparer(a,b){
return a.title.localeCompare(b.title)
};
For sorting an array with a custom setting do as following:
Create an array with a custom order of alphabets:
var alphabets = ["A", "B", "C", "Č", "Ć", "D","Dž","Đ","E","F","G","H","I","J","K","L","Lj","M","N","Nj","O","P","R","S", "ÛŒ","T","U","V","Z","Ž"];
Create a list of test array:
var testArrray = ["B2","D6","A1","Ć5","Č4","C3"];
Create a sort function name:
function OrderFunc(){
testArrray.sort(function (a, b) {
return CharCompare(a, b, 0);
});
}
create the CharCompare function(index: sort "AAAB" before "AAAC"):
function CharCompare(a, b, index) {
if (index == a.length || index == b.length)
return 0;
//toUpperCase: isn't case sensitive
var aChar = alphabets.indexOf(a.toUpperCase().charAt(index));
var bChar = alphabets.indexOf(b.toUpperCase().charAt(index));
if (aChar != bChar)
return aChar - bChar
else
return CharCompare(a,b,index+1)
}
Call OrderFunc for sorting the testArray(the result will be : A1,B2,C3,Č4,Ć5,D6).
Test Online
Good Luck
Use The Intl.Collator like you will get perfect sorting result
function letterSort(lang, letters) {
letters.sort(new Intl.Collator(lang).compare);
return letters;
}
console.log(letterSort('gu', ['છ','ક','ખ']));
// expected output: Array ["a", "ä", "z"]
console.log(letterSort('sv', ['a','z','ä']));
// expected output: Array ["a", "z", "ä"]
More detail you can check here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collator