0

how to sort number with string array in jquery

["8h 40m", "5h 0m", "8h 55m", "5h 10m", "13h 0m", "3h 50m", "23h 30m", "3h 0m", "10h 55m", "9h 30m", "1h 25m", "1h 25m", "1h 25m", "1h 20m", "13h 30m", "5h 55m", "13h 10m", "10h 25m", "14h 50m", "1h 30m", "1h 40m", "1h 40m", "1h 40m", "9h 10m", "13h 15m"]

Please suggest.

var _sortDurationArray = _durationArray.sort(function (a, b) {
                  var contentA =parseInt(a);
                  var contentB =parseInt(b);
                  return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
               })

Output:

["1h 40m", "1h 25m", "1h 40m", "1h 20m", "1h 40m", "1h 25m", "1h 25m", "1h 30m", "3h 0m", "3h 50m", "5h 10m", "5h 0m", "5h 55m", "8h 40m", "8h 55m", "9h 30m", "9h 10m", "10h 25m", "10h 55m", "13h 30m", "13h 10m", "13h 0m", "13h 15m", "14h 50m", "23h 30m"]

Required output is.

["1h 20m", "1h 25m", "1h 25m", "1h 25m", "1h 30m", "1h 40m", "1h 40m","3h 0m", "3h 50m", "5h 0m", "5h 10m", "5h 55m", "8h 40m", "8h 55m", "9h 10m", "9h 30m", "10h 55m", "10h 25m", "13h 0m", "13h 10m", "13h 15m", "13h 30m", "14h 50m", "23h 30m"]

2 Answers 2

2

Basically you need to compare the minutes values by converting the time value like below and then need to compare them:

var _durationArray = ["8h 40m", "5h 0m", "8h 55m", "5h 10m", "13h 0m", "3h 50m", "23h 30m", "3h 0m", "10h 55m", "9h 30m", "1h 25m", "1h 25m", "1h 25m", "1h 20m", "13h 30m", "5h 55m", "13h 10m", "10h 25m", "14h 50m", "1h 30m", "1h 40m", "1h 40m", "1h 40m", "9h 10m", "13h 15m"]


var _sortDurationArray = _durationArray.sort(function(a, b) {
  var contentA = getMin(a);
  var contentB = getMin(b);
  return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
});

console.log(_sortDurationArray);

function getMin(time) {
  var timearr = time.split(" ");
  var hr = timearr[0].replace("h", "");
  var min = timearr[1].replace("m", "");

  var totMin = parseInt(hr) * 60 + parseInt(min);
  return totMin;
}

Sign up to request clarification or add additional context in comments.

Comments

0

Short but effective:

arr.sort(function(a,b){
    a = a.split(' ').map(e => parseInt(e));
    b = b.split(' ').map(e => parseInt(e));

    return a[0] != b[0] ? a[0] - b[0] : a[1] - b[1]
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.