Danigoodw
Danigoodw

Reputation: 379

How to order an array by containing elements order in pure JS

Say i have an array of 10 elements, that some of them are actually children of some of the other elements. How would i go about ordering this array so to top parents are first in order, and the deepest children are last?

[
    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
]

In this particular case, the form element might be the toppest parent, but the solution I'm looking for is to create such an order without any such knowledge

Upvotes: 0

Views: 85

Answers (1)

Ori Drori
Ori Drori

Reputation: 192317

You can use Array.map() to create a score for each element - the score is based on the number of parent the element has. Now you can sort the elements by their score, and extract the elements using another 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>

Upvotes: 1

Related Questions