Unsorted array [input] :
["> 30 days", "< 7 days", "< 30 days", "< 10 days"];
The format of an elements in array will always be like : </> X days
Requirement :
Above mentioned array should be sorted as per the greater then (>)
and lesser then symbol (<)
and also keep the number of days in mind (less number of days should come first).
Expected Array [output] :
["< 7 days", "< 10 days", "< 30 days", "> 30 days"];
Tried so far :
I tried Array.sort() function but did not get expected output.
var arr = ["> 30 days", "< 7 days", "< 30 days", "< 10 days"];
var sortedArr = arr.sort();
console.log(sortedArr); // ["< 30 days", "< 10 days", "< 7 days", "> 30 days"]
In JavaScript, we can sort the elements of an array easily with a built-in method called the sort( ) function. However, data types (string, number, and so on) can differ from one array to another.
Even if objects have properties of different data types, the sort() method can be used to sort the array.
You could sort by numbers and if a comparison sign is available, then take for the same numerical value the delta of both offsets, which reflects the order of comparison.
var array = ["> 30 days", "< 7 days", "30 days", "< 10 days", "> 10 days", "< 11 days", "42 days", ">= 42 days", "> 42 days", "<= 42 days", "< 42 days"];
array.sort(function (a, b) {
function getV(s) {
return {
value: s.match(/\d+/),
offset: { '<': -2, '<=': -1, null: 0, '>=': 1, '>': 2 }[s.match(/[<>]={0,1}(?=\s*\d)/)]
};
}
var aa = getV(a),
bb = getV(b);
return aa.value - bb.value || aa.offset - bb.offset;
});
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
First/former solution
You could parse the string and use it for applying a correction value to the number - then sort accordingly.
{ '>': 0.1, '<': -0.1, null: 0 }[s.match(/[<>](?=\s*\d)/)] + +s.match(/\d+/)
object with correction values
{ '>': 0.1, '<': -0.1, null: 0 }
get the sign with a regular expression and use it as key for the object
s.match(/[<>](?=\s*\d)/)
then add the number part of the string
+ +s.match(/\d+/)
var array = ["> 30 days", "< 7 days", "30 days", "< 10 days"];
array.sort(function (a, b) {
function getV(s) {
return { '>': 0.1, '<': -0.1, null: 0 }[s.match(/[<>](?=\s*\d)/)] + +s.match(/\d+/);
}
return getV(a) - getV(b);
});
console.log(array);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With