以特殊方式排序数组

时间:2014-09-25 15:02:54

标签: javascript arrays sorting

排序数组时遇到问题。关于这些排序算法我不是最聪明的。 该数组应具有以下结构:

 var arr = [
 [week, IssuesPriority1, IssuesPriority2, IssuesPriority3],
 [week, IssuesPriority1, IssuesPriority2, IssuesPriority3],
 [week, IssuesPriority1, IssuesPriority2, IssuesPriority3],
 ...
 ];

因此,对于每周都存在许多优先级非常高,高,中等的问题。 需要在此结构中解析的字符串如下:

 var string =
 "26|3|1,27|6|1,28|7|1,29|2|1,30|2|1,31|2|1,32|2|1,33|3|1,
  35|1|1,34|2|1,36|0|1,37|0|1,38|1|1,26|11|2,27|10|2,28|9|2,
  29|13|2,30|10|2,31|8|2,32|10|2,33|12|2,34|14|2,35|11|2,
  36|11|2,37|12|2,38|14|2,27|17|3,26|13|3,29|26|3,28|21|3,30|25|3,
  31|20|3,34|30|3,32|18|3,33|25|3,35|33|3,36|28|3,38|28|3,37|27|3";

  var arr = string.split(",");

  for(var i = 0; i < arr.length; i++){
      var currentArr = arr[i].split("|");
      var week = currentArr[0];
      var issues = currentArr[1];
      var priority = currentArr[2];
  }

我缺乏以理想方式对其进行排序的想法。你能救我吗?

2 个答案:

答案 0 :(得分:0)

我认为你根本不想要任何排序。您正在寻找分组

var arr = string.split(",");
var weeks = {};
for (var i = 0; i < arr.length; i++) {
    var currentArr = arr[i].split("|");
    var week = currentArr[0];
    var issue = currentArr[1];
    var priority = currentArr[2];
    if (!(week in weeks))
        weeks[week] = {1:[], 2:[], 3:[]};
    // if the number of issues levels were unknown,
    // you'd start with an empty object instead
    // and create the arrays dynamically in a manner similar to the weeks
    weeks[week][priority].push(issue);
}
return Object.keys(weeks).map(function(week) {
    return [week, weeks[week][1], weeks[week][2], weeks[week][3]];
});

(要按周编号排序,请在sort(function(a,b){return a-b})来电之前添加.map()

答案 1 :(得分:0)

在您的情况下,我建议先将值放入数组中。在第二步中,我将使用sort method对数组进行排序。

function getSortedArrayByString(myString) {
    var arraySplittedString, i, tmpValueArray, tmpInnerArray, resultingArray;

    arraySplittedString = myString.split(",");
    resultingArray = [];

    for(i = 0; i < arraySplittedString.length; i++){
        // tmpArray has the format of [<week>, <IssuesPriority1>, <IssuesPriority2>]
        tmpValueArray = arraySplittedString[i].split("|");
        // Push it in the new array.
        resultingArray.push(tmpValueArray);
    }

    // Sort array by weeks ascending. 
    resultingArray.sort( function (a, b) {
        return a[0] - b[0];
    });

    return resultingArray;
}

正在运行fiddle

如果您还想按问题排序,您可以自定义内部排序功能。

使用此解决方案,所有值都保存为字符串。您可以使用parseInt function转换它们。