Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript : Sorting an array

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"]
like image 948
Creative Learner Avatar asked Jul 18 '17 09:07

Creative Learner


People also ask

Can you sort an array in JavaScript?

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.

What is the correct method to use in JavaScript sorting arrays?

Even if objects have properties of different data types, the sort() method can be used to sort the array.


1 Answers

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);
like image 188
Nina Scholz Avatar answered Oct 14 '22 04:10

Nina Scholz