Sorry if the title isn't very descriptive! I am trying to reorder an observable array based on the order of another observable array. For example
self.tagging_fields = ko.observableArray(['field_1', 'field_2', 'field_3'])
function Tag(data){
var self = this;
self.field_name = ko.observable(data.field_name);
}
var example_tags = [
new Tag({field_name : "field_3"}),
new Tag({field_name : "field_2"}),
new Tag({field_name : "field_1"})
]
self.tags = ko.observableArray(example_tags);
//This is what I want to achieve
var after_sorting = [
{ field_name : "field_1" },
{ field_name : "field_2" },
{ field_name : "field_3" }
]
What I'm trying to do is sort the order of the tag objects by field_name within self.tags based on the order they appear within self.tagging_fields. Could anyone help me out to write a custom sort function for this operation
Update:
I have managed to achieve what I want within the output foreach
I've worked around it by doing a comparison within the output foreach
<div data-bind="foreach: { data: $root.tagging_fields, as : 'tagging_field' }">
<div data-bind="foreach: { data : line.tags, as : 'tag' }">
<div data-bind="if: tag.field_name() === tagging_field">
<span data-bind="text: tag.field_name"></span>
<input data-bind="value: tag.value"/><br/>
</div>
</div>
</div>`
I know it's probably not the best way but it works!
Something like (untested):
self.tags.sort(function(left, right) {
var leftIndex = self.tagging_fields.indexOf(left);
var rightIndex = self.tagging_fields.indexOf(right);
return leftIndex == rightIndex
? 0 : (leftIndex < rightIndex ? -1 : 1)
});
See doc here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.