我怎么能数组排序,但排除某些元素(在数组中的相同位置保持) [英] How can I sort an array, yet exclude certain elements (to be kept at the same position in the array)
本文介绍了我怎么能数组排序,但排除某些元素(在数组中的相同位置保持)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这将在Javascript(jQuery的)来实现,但我想,该方法可以在任何语言中使用。
This will be implemented in Javascript (jQuery) but I suppose the method could be used in any language.
我有一个项目数组,我需要进行排序。 然而有数组中的某些项必须保持在同一位置(同一索引)。
I have an array of items and I need to perform a sort. However there are some items in the array that have to be kept in the same position (same index).
问题该数组是从列表建立<李>
元素和我使用的.data()附加到列表项作为值值其排序。
The array in question is build from a list of <li>
elements and I'm using .data() values attached to the list item as the value on which to sort.
什么方法是最好的吗?
<ul id="fruit">
<li class="stay">bananas</li>
<li>oranges</li>
<li>pears</li>
<li>apples</li>
<li class="stay">grapes</li>
<li>pineapples</li>
</ul>
<script type="text/javascript">
var sugarcontent = new Array('32','21','11','45','8','99');
$('#fruit li').each(function(i,e){
$(this).data('sugar',sugarcontent[i]);
})
</script>
我想用下面的结果排序列表...
I want the list sorted with the following result...
<ul id="fruit">
<li class="stay">bananas</li> <!-- score = 32 -->
<li>pineapples</li> <!-- score = 99 -->
<li>apples</li> <!-- score = 45 -->
<li>oranges</li> <!-- score = 21 -->
<li class="stay">grapes</li> <!-- score = 8 -->
<li>pears</li> <!-- score = 11 -->
</ul>
谢谢!
推荐答案
算法是:
- 提取和排序没有打上
物品留
-
合并
停留
项目和排序的项
var sugarcontent = new Array(32, 21, 11, 45, 8, 99);
var items = $('#fruit li');
items.each(function (i) {
$(this).data('sugar', sugarcontent[i]);
// Show sugar amount in each item text - for debugging purposes
if ($(this).hasClass('stay'))
$(this).text("s " + $(this).text());
else
$(this).text(sugarcontent[i] + " " + $(this).text());
});
// Sort sortable items
var sorted = $(items).filter(':not(.stay)').sort(function (l, r) {
return $(l).data('sugar') - $(r).data('sugar');
});
// Merge stay items and sorted items
var result = [];
var sortedIndex = 0;
for (var i = 0; i < items.length; i++)
if (!$(items[i]).hasClass('stay')) {
result.push(sorted[sortedIndex]);
sortedIndex++;
}
else
result.push(items[i]);
// Show result
$('#fruit').append(result);
这篇关于我怎么能数组排序,但排除某些元素(在数组中的相同位置保持)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文