【问题标题】:How to order an array by containing elements order in pure JS如何通过在纯JS中包含元素顺序来对数组进行排序
【发布时间】:2019-01-09 17:57:59
【问题描述】:

假设我有一个包含 10 个元素的数组,其中一些实际上是其他一些元素的子元素。我将如何对这个数组进行排序,以便顶级父母排在第一位,而最深的孩子排在最后?

[
    input,
    select,
    radio,
    div (containing some of the form elements in the array),
    h2,
    div (containing the h2 in the array),
    form,
    textarea,
    a,
    span
]

在这种特殊情况下,表单元素可能是最顶层的父元素,但我正在寻找的解决方案是在没有任何此类知识的情况下创建这样的订单

【问题讨论】:

标签: javascript arrays javascript-objects


【解决方案1】:

您可以使用Array.map() 为每个元素创建一个分数 - 分数基于该元素的父级数量。现在您可以按分数对元素进行排序,并使用另一个 Array.map() 提取元素:

const els = Array.from(document.querySelectorAll('div *'))
  .map(el => {
    let score = 0, p = el;
    
    while(p = p.parentNode) { score++; }
    
    return [el, score];
  })
  .sort(([ea, sa], [eb, sb]) => sa - sb)
  .map(([el]) => el)

console.log(els);
<div>
  <form>
    <div class="form-els-container">
      <input>
      <select></select>
      <input type="radio">  
      <textarea></textarea>
    </div>
  </form>
  <div class="h2-container">
    <h2>H2</h2>
  </div>
  <a>a</a>
  <span></span>
</div>

【讨论】:

    猜你喜欢
    • 2015-02-17
    • 2019-09-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-27
    • 2010-09-18
    • 1970-01-01
    • 2020-09-04
    • 2015-06-28
    相关资源
    最近更新 更多