按自定义变量排序数组

时间:2016-02-17 09:13:02

标签: javascript jquery arrays sorting

$("#show_times_available_" + pos).find("td span").parent().each(function(){ 
    array.push($(this).attr("id")); 
    array = array.sort();
});

我的数组获取所有元素并获取它们的ID并将其推送到数组中,因此我的数组将最终为;

[ "mon_0600-0", "sun_0700-0", "thu_0600-0", "thu_0700-0", "tue_0300-0", "wed_0700-0" ];

我想要做的是每次将新元素推入数组时将这些元素排序为(mon,tue,wed等等)。这样我的数组最终会成为;

[ "mon_0600-0", "tue_0300-0", "wed_0700-0", "thu_0600-0", "thu_0700-0", "sun_0700-0" ];

使用基本sort()函数将按字母顺序排列,我知道sort()函数可以接受另一个函数。我只是不确定如何在vanilla javascript或jQuery中设置它。是否有一种情况或使用when()then()对这些进行排序?我搜索谷歌和所有的搜索引擎优化,但没有。

6 个答案:

答案 0 :(得分:2)

如您所说,您需要将自定义功能传递给sort()。在这里,您需要将日期与时间分开,然后返回日期部分与时间部分的比较(如果日期相同):

var arr = ["mon_0600-0", "sun_0700-0", "thu_0600-0", "thu_0700-0", "tue_0300-0", "wed_0700-0"];

// store the order of the days
var days = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];

var arrSorted = arr.sort(function(a, b) {
  // a and b are two times to compare

  // split each into days and times, e.g ["mon", "0600-0"]
  var aSplit = a.split("_");
  var bSplit = b.split("_");
  
  // get the index of the days to compare
  var dayA = days.indexOf(aSplit[0]);
  var dayB = days.indexOf(bSplit[0]);
  
  // if days are the same, compare the times using normal String comparison
  // if days are different, return the comparison of their position in the array
  return dayA == dayB ?
  	aSplit[1].localeCompare(bSplit[1])
  	: dayA - dayB;
});

console.log(arrSorted);

答案 1 :(得分:1)

使用.sort时,您可以指定进行比较的函数。

您的函数必须接收两个参数,例如compare(a,b),如果a首先返回小于零,如果两者必须占据相同位置则返回零,如果b则大于零必须在a之后。

var array = ["X123", "X0072", "X04"];

var compareFunction = function(a,b) {
  var _a = parseInt(a.substring(1));
  var _b = parseInt(b.substring(1));
  return _a-_b;
}

$('#original').text(JSON.stringify(array));

array.sort();
$('#sort').text(JSON.stringify(array));

array.sort(compareFunction);
$('#customSort').text(JSON.stringify(array));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>Original:</p>
<pre id="original"></pre>

<p>Sort:</p>
<pre id="sort"></pre>

<p>Custom sort:</p>
<pre id="customSort"></pre>

答案 2 :(得分:1)

我建议你使用一个以排序方式包含日期的数组:

<script type="text/javascript">
var validator="";

$(document).ready(function(){

var max_length_rules= <?php echo json_encode($valid_rules); ?>;

validator=$("#baby_book").validate();

     $.each(max_length_rules,function(k,v){

             $.each(v, function(key, value){

                   $('input[id="'+key+'"]').rules('add',"required"); 
                });
        });

});

function validatefilesizeform(type)
{
    if(type == 'save')
     {
         document.baby_book.sec_submit.value="save";

         if(validator.form())
         {
            document.baby_book.submit();
         }
    }

</script>

然后您可以使用索引对数据进行排序:

var days = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];

答案 3 :(得分:1)

这里你使用自定义排序功能

// your array
array = [ "mon_0600-0", "sun_0700-0", "thu_0600-0", "thu_0700-0", "tue_0300-0", "wed_0700-0" ];

// the order stored in an object
daynames={
    mon:1,
    tue:2,
    wed:3,
    thu:4,
    fri:5,
    sat:6,
    sun:7
}

// the custom sort function which gets the value for the dayname-key and compares
function SortByDayName(a, b){

  // get the value of dayname + the time 
  var aName = daynames[a.substr(0,3)] + a.substr(4,7);;
  var bName = daynames[b.substr(0,3)] + b.substr(4,7);; 
  return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
}

// apply sort
array.sort(SortByDayName);

// output:
["mon_0600-0", "tue_0300-0", "wed_0700-0", "thu_0600-0", "thu_0700-0", "sun_0700-0"]

答案 4 :(得分:1)

你可以使用这个功能来做到这一点

var array = ["mon_0600-0", "sun_0700-0", "thu_0600-0", "thu_0700-0", "tue_0300-0", "wed_0700-0"],
  sort = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];

var sortondays = function() {
  var newArray = [];
  for (i = 0; i < sort.length; i++) {
    var t = sort[i];
    for (x = 0; x < array.length; x++) {
      if (array[x].startsWith(t)) {
        newArray.push(array[x])
      }
    }
  }
  return newArray;
}
console.log(sortondays());

答案 5 :(得分:1)

这个问题对于Sorting with map来说是完美的,因为对于一个元素只进行了一次分割和查找,而不是为每个排序回调。

// the array to be sorted
var data = ["mon_0600-0", "sun_0700-0", "thu_0600-0", "thu_0700-0", "tue_0300-0", "wed_0700-0"];

// temporary array holds objects with position and sort-value
var mapped = data.map(function (el, i) {
    var value = el.split('_'), day;
    return {
        index: i,
        day: { mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6, sun: 7 }[value[0]] || 0,
        hour: value[1]
    };
})

// sorting the mapped array containing the reduced values
mapped.sort(function (a, b) {
    return a.day - b.day || a.hour.localeCompare(b.hour);
});

// container for the resulting order
var result = mapped.map(function (el) {
    return data[el.index];
});

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');