简体   繁体   English

按键值对JavaScript数组中的对象进行排序

[英]Sorting Objects in a JavaScript Array by a Key Value

I may have come up with an incredibly crude way to get this sort of thing accomplished, but I figured that I'd ask the many experts present here at SO. 我可能想出了一种非常粗略的方法来完成这种事情,但是我认为我想请SO的许多专家参加。 Basically, I have an array that looks something like the following: 基本上,我有一个看起来像下面的数组:

var bugs = [
    {
        id: "197526",
        title: "Updating Lighthouse",
        summary: "Enhancing the UI of Lighthouse",
        status: "Active",
        project: "Lighthouse",
        area: "Internal Web Applications",
        hours: 19
    },
    {
        id: "190328",
        title: "Adding Login Authentication to Lighthouse",
        summary: "Create a login authentication process for Lighthouse",
        status: "Active",
        project: "Lighthouse",
        area: "Administration",
        hours: 12
    },
    ...
    {
        id: "187562",
        title: "Create a Maintenance Page",
        summary: "Create a maintenance page to be displayed with the company site is down",
        status: "Resolved",
        project: "Other",
        area: "Internal Web Projects",
        hours: 4
    },
];

Basically, the array holds several "bugs," each with an id, title, summary, status, project, area, and hours property. 基本上,数组包含几个“错误”,每个错误都有一个id,标题,摘要,状态,项目,区域和hours属性。 Each of these bugs are going to be displayed on my web application, but I allow the user to select how they will be grouped; 这些错误中的每一个都将显示在我的Web应用程序上,但是我允许用户选择如何将它们分组。 either by status, project, or area. 按状态,项目或区域划分。 Depending upon which of the three they select from a select box above, I want to be able to sort through all of the bugs and group them by whichever category they chose. 根据他们从上面的选择框中选择的三个中的哪一个,我希望能够对所有错误进行排序,并按照他们选择的类别对它们进行分组。 Then, when it comes to displaying them, have a simple header for each present option for that category. 然后,当要显示它们时,对于该类别的每个当前选项都有一个简单的标题。 For example, if they were to sort by status, it would be something like: 例如,如果要按状态排序,则将类似于:

Group By: Status

Active
------
Bug with status: "active"
Bug with status: "active"
Bug with status: "active"

Resolved
--------
Bug with status: "resolved"
Bug with status: "resolved"

Should I iterate through the entire array of bugs and, based on the category to sort by, simply create a new array for each possible option of that category and add the appropriate bugs to them? 我是否应该遍历整个bug数组,并根据要分类的类别,简单地为该类别的每个可能选项创建一个新数组,并向其中添加适当的bug? So in the case above, create new arrays var activeBugs = [] and var resolvedBugs = [] ? 因此,在上述情况下,创建新数组var activeBugs = []var resolvedBugs = [] var activeBugs = [] var resolvedBugs = []吗? If so, my problem would then be knowing what possible options there are. 如果是这样,那么我的问题将是知道有哪些可能的选择。 Should I then first iterate through the entire bugs array to see what possible options are present for the desire group category before creating these new arrays? 然后,在创建这些新数组之前,我是否应该首先遍历整个bug数组以查看欲望组类别存在哪些可能的选项?

What's the best way to do this without resorting to other jQuery plugins? 不借助其他jQuery插件的最佳方法是什么?

Will the user have a copy off all the bugs? 用户会得到所有错误的副本吗? or do you just send, lets say, the first 100? 还是只发送前100个?

  • If you send the first 100, the I suggest you to make 3 arrays on the server, which hold pointers to the objects, and every new bug is inserted according to its position. 如果您发送前100个,我建议您在服务器上建立3个数组,其中包含指向对象的指针,并且根据其位置插入每个新的错误。 and then just send from the list that was requested. 然后只需从请求的列表中发送即可。 that should be fast because you just pull information. 那应该很快,因为您只是获取信息。 and the sorting is at insertion time. 并且排序是在插入时进行的。 (all 'sorting' is done when the bug is added - this assumes that you view info more often that you edit it!) (添加错误时,所有“排序”都已完成-假设您编辑信息时查看信息的频率更高!)
  • If the client holds a copy of all the data, then just re-sort it on the client with javascript. 如果客户端持有所有数据的副本,则只需使用javascript在客户端上对其重新排序即可。 shouldn't take too much time. 不应花费太多时间。 this saves you bandwidth, and assumes you don't have that much bugs so you can show all of them at once. 这样可以节省带宽,并假设您没有太多错误,因此可以一次显示所有错误。

Sort the array by status using array.sort. 使用array.sort按状态对数组进行排序。 Iterate through the array remembering what the previous iteration's .status property was. 遍历数组,记住上一次迭代的.status属性是什么。 When it changes, create a new visual representation. 更改时,创建一个新的视觉表示。

bugs.sort(mySortFunc);

var lastStatus = '';
for (var i=0, b; b = bugs[i]; i++) {
  if (b.status != lastStatus) {
    //output a header for the new status b.status
    document.write(b.status + '<br>----<br>');
    lastStatus = b.status;
  }
  // output the bug
  document.write(b.title + '<br>');
}

Warning: Eventually you'll wish you had let the database do all the sorting/grouping/paging/etc. 警告:最终,您希望您让数据库完成所有排序/分组/分页/等操作。

Here's an example using .filter() as I described in my comment: 这是我在评论中描述的使用.filter()的示例:

var active_bugs = bugs.filter(function(bug) {
    return bug.status === "active";
});

To elaborate on my comment questioning the need to sort/filter at all, can you do something (very roughly) like this in your display logic? 要详细说明我对根本是否需要排序/过滤的质疑,您可以在显示逻辑中做(大致)这样的事情吗?

$('#SortOrder').live('change', function() {
  var groupby = $(this).val();

  $('#Bugs').empty();

  for (var i = 0; i < bugs.length; i++) {
    if (!document.getElementById(bugs[i][groupby])) {
        $('<h3>', { text: bugs[i][groupby] }).appendTo('#Bugs');

        $('<ul>', {
            id: bugs[i][groupby]
        }).appendTo('#Bugs');
    }

    var $li = $('<li>', {
        text: bugs[i].title
    });

    $('#Bugs').find('#' + bugs[i][groupby]).append($li);
  }
});

Working demo: http://jsfiddle.net/TTApQ/1/ 工作演示: http : //jsfiddle.net/TTApQ/1/

That way there's no sorting or filtering at all, and you only need to make one pass over the array. 这样,根本就没有排序或过滤,您只需要对数组进行一次遍历。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM