简体   繁体   English

Javascript按子数组ID对数组进行排序

[英]Javascript sort an array by subarray id

I have an array under bahrein that I would like ordered by the index of each item. 我在bahrein下有一个数组,我想按每个项目的索引排序。 My bare code is as shown below. 我的裸露代码如下所示。

 var bahrein = [ {id: 1, name: "Josef"}, {id: 3, name: "Billy"}, {id: 0, name: "Jane"}, {id: 2, name: "Mack"} ]; for (i = 0; i < bahrein.length; i++){ document.getElementById("show").innerHTML += "<p>"+bahrein[i].name+"</p>"; } 
 <div id="show"></div> 

I have ids assigned for each item, but I placed them out of order. 我为每个项目分配了ID,但是我将它们按顺序放置。 What I would like to know is how to programatically use the sort() function to list the names on my list in order. 我想知道的是如何以编程方式使用sort()函数按顺序列出列表中的名称。

Right now my innerHTML shows the list in the order they are written (ie: Josef , Billy , Jane , and Mack ). 现在,我的innerHTML按书写顺序显示列表(即: JosefBillyJaneMack )。 I want to show them in the order of their ID (ie: Jane , Josef , Mack , Billy ). 我想按ID的顺序显示它们(即: JaneJosefMackBilly )。

You can use sort() method on your data and then append it to html. 您可以对数据使用sort()方法,然后将其附加到html。

 var bahrein = [{id: 1, name: "Josef"},{id: 3, name: "Billy"},{id: 0, name: "Jane"},{id: 2, name: "Mack"}]; let show = document.getElementById("show") bahrein .sort((a, b) => a.id - b.id) .forEach(e => show.innerHTML += `<p>${e.name}</p>`) 
 <div id="show"></div> 

You could also create string of sorted html and then append it html. 您还可以创建已排序的html字符串,然后将其附加为html。

 var bahrein = [{id: 1, name: "Josef"},{id: 3, name: "Billy"},{id: 0, name: "Jane"},{id: 2, name: "Mack"}]; let sorted = bahrein .sort((a, b) => a.id - b.id) .map(e => `<p>${e.name}</p>`) .join('') document.getElementById("show").innerHTML = sorted 
 <div id="show"></div> 

It doesn't answer your question, but you can use "lodash" to do the same. 它不能回答您的问题,但是您可以使用“ lodash”执行相同的操作。

var bahrein = [
    {id: 1, name: "Josef"},
    {id: 3, name: "Billy"},
    {id: 0, name: "Jane"},
    {id: 2, name: "Mack"}
];

bahrein = _.orderBy(bahrein , ['id'],['asc']);

You can learn more about it here . 您可以在此处了解更多信息。

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

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