1

I have an Observable array in knockout with arrays inside, there is an item inside each of the arrays called 'time'. How would I order the arrays inside my observable array so that they are in order, from low to high, based on the value of the item. The values are in Hour:Minute:Second format.

function viewModel() {
  var self = this;
  
  self.myObservable = ko.observableArray([
  {time: "01:00:00", name: 'frank'},
  {time: "05:30:00", name: 'bob'},
  {time: "03:00:00", name: 'bill'},
  {time: "00:00:21", name: 'john'},
  {time: "00:12:00", name: 'paul'}
  ])
}

2 Answers 2

1

Knockout has built-in methods for observableArray which work similar to Array.prototype. You can sort it by using localeCompare

function viewModel() {
  var self = this;

  self.myObservable = ko.observableArray([
      { time: "01:00:00", name: 'frank' },
      { time: "05:30:00", name: 'bob' },
      { time: "03:00:00", name: 'bill' },
      { time: "00:00:21", name: 'john' },
      { time: "00:12:00", name: 'paul' }
    ]);

  self.sort = function() {
    self.myObservable.sort((a, b) => a.time.localeCompare(b.time))
  }
}

ko.applyBindings(new viewModel)
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<!-- ko foreach: myObservable -->
  <span data-bind="text: time"></span><br>
<!-- /ko -->

<button data-bind="click: sort">Sort</button>

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

1 Comment

Yes, however I think I didn't give the example of my problem clearly, my issues is that I need to order the observable array using a value in HH:MM:SS format. Do you know how I would do that? I have changed my question with a new example. Thanks
1

You should use the sort() function.

    self.myObservable.sort(function (left, right) {
        return left.age === right.age ? 0
             : left.age < right.age ? -1
             : 1;
    });

2 Comments

Yes, however I think I didn't give the example of my problem clearly, my issues is that I need to order the observable array using a value in HH:MM:SS format. Do you know how I would do that? I have changed my question with a new example. Thanks
The declaration time: 01:00:00 is not valid in JavaScript, perhaps you meant time: '01:00:00'? In any case, within the comparison function you could convert both values (left and right) into seconds and then compare them.

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.