0

I have an array under bahrein that I would like ordered by the index of each item. 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. What I would like to know is how to programatically use the sort() function to list the names on my list in order.

Right now my innerHTML shows the list in the order they are written (ie: Josef, Billy, Jane, and Mack). I want to show them in the order of their ID (ie: Jane, Josef, Mack, Billy).

Jason Chen
  • 2,487
  • 5
  • 25
  • 44
  • 3
    Possible duplicate of [Sorting an array of JavaScript objects](https://stackoverflow.com/questions/979256/sorting-an-array-of-javascript-objects) – Charlie Martin Dec 12 '17 at 22:20

2 Answers2

1

You can use sort() method on your data and then append it to 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.

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>
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
-1

It doesn't answer your question, but you can use "lodash" to do the same.

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.

Saeid
  • 1,573
  • 3
  • 19
  • 37