创建按数字排序的新数组

Create new array sorted by number

如何创建新元素并按“data-number”中的数字排序?知道怎么做吗?我找到了一个 sort method with,但是如何在 for 循环中插入?

“parent-sort”的结果应该是这样的:

<div id="parent-sort">
    <div class="child" id="child2" data-name="1">1</div>
    <div class="child" id="child4" data-name="2">2</div>
    <div class="child" id="child1" data-name="3">3</div>
    <div class="child" id="child3" data-name="4">4</div>
</div>

代码:

function myFunction() {
    elementsort = document.getElementById("parent").children;
    for (i = 0; i < elementsort.length; i++) {
    var element_id = elementsort[i].id;
    var element_class_name = elementsort[i].className;
    var element_inner_html = elementsort[i].innerHTML;
    var data_name = elementsort[i].getAttribute("data-name");
    
    const new_div = document.createElement("div");
    new_div.id = element_id;
    new_div.className = element_class_name;
    new_div.innerText = element_inner_html;
    new_div.setAttribute("data-name", data_name);
    document.getElementById("parent-sort").appendChild(new_div);
    }
}
<div id="parent">
    <div class="child" id="child1" data-name="3">3</div>
    <div class="child" id="child2" data-name="1">1</div>
    <div class="child" id="child3" data-name="4">4</div>
    <div class="child" id="child4" data-name="2">2</div>
</div>

<div id="parent-sort">
</div>

<button onclick="myFunction()">Click me</button>

您可以使用以下代码:

function myFunction() {
  elementsort = document.getElementById("parent").children;
  const sortedList = [...elementsort].sort((a, b) => {
    const c = a.textContent,
      d = b.textContent;
    return c < d ? -1 : c > d ? 1 : 0;
  });
  for (const item of sortedList) {
    document.getElementById("parent-sort").appendChild(item);
  }
}
<div id="parent">
  <div class="child" id="child1" data-name="3">3</div>
  <div class="child" id="child2" data-name="1">1</div>
  <div class="child" id="child3" data-name="4">4</div>
  <div class="child" id="child4" data-name="2">2</div>
</div>

<div id="parent-sort">
</div>

<button onclick="myFunction()">Click me</button>