[英]How to sort an Observable Array based on a certain item inside each Array
I have an Observable array in knockout with arrays inside, there is an item inside each of the arrays called 'time'. 我在淘汰赛中有一个Observable数组,里面有数组,每个数组中都有一个称为“时间”的项目。 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.
值以Hour:Minute:Second格式显示。
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'} ]) }
Knockout has built-in methods for observableArray
which work similar to Array.prototype
. 淘汰赛具有
observableArray
内置方法 ,其工作方式类似于Array.prototype
。 You can sort
it by using localeCompare
您可以使用
localeCompare
对其进行sort
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.