Steps for sorting an array based on the order of its elements in vanilla JavaScript

If I have an array of 10 elements, where some are children of others, how can I rearrange this array so that the top parents come first and the deepest children come last?

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

In this scenario, the form element might be the highest-level parent, but I'm seeking a solution to order them without any prior knowledge of their parent-child relationships.

Answer №1

To assign a score to each element based on the number of parents it has, you can utilize the Array.map() method. Once the scores are determined, you can proceed to sort the elements by their respective scores and then extract the elements using yet another Array.map():

const elements = Array.from(document.querySelectorAll('div *'))
  .map(element => {
    let score = 0, parentElement = element;
    
    while(parentElement = parentElement.parentNode) { score++; }
    
    return [element, score];
  })
  .sort(([eleA, scoreA], [eleB, scoreB]) => scoreA - scoreB)
  .map(([element]) => element)

console.log(elements);
<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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Deleting a task in a React functional component with hooks is simple and can be done by

When attempting to use the handleDelete function to delete a task, I noticed something strange happening. Every time I click the addTodos function, the handleDelete is automatically triggered. Why is this happening? My goal is to retrieve the id when clic ...

React has reached the maximum update depth limit

In my current project, I am developing a react application that involves a user inputting a search term and receiving an array of JSON data from the backend. On the results page, I have been working on implementing faceted search, which includes several fi ...

D3 bar chart displaying identical values but with varying data sets

<!DOCTYPE html> <html lang='en'> <head> <meta charset="UTF-8"/> <title>Interactive Bar Chart using D3</title> <script src="https://d3js.org/d3.v4.min.js"></script> </head> <b ...

Converting 1D array values into 2D coordinates

Currently, I am in the process of converting the array index to 2d coordinates. I am attempting to achieve the 2D reverse functionality, as described in this post: The issue arises during the x-axis division (considering a width of 3), where the result i ...

The table value is only updated once with the onclick event, but the updated value is not displayed when the event is clicked again

I am facing an issue with updating names in a table through a modal edit form. The first name update works perfectly, but the second update does not reflect in the table. I want every change made in the modal edit form to be instantly displayed in the tabl ...

Angular disrupts the functionality of jQuery slideshow

While working on this template, I encountered issues with the functionality after integrating Angular into the application. Although I managed to fix most of them, I'm facing difficulty getting the slideshow to function properly. Here is the HTML cod ...

Unable to animate a second click using jQuery/CSS

I'm having an issue with animating on click using CSS. The animation works fine on the first click, but it doesn't work on the second click. This is because the click event is being overridden by jQuery to enable the dropdown menu to open onClick ...

Personalizing the label of a select input using materialui

Working on customizing a select element using the "styled" method: const StyledSelect = styled(Select)` height: 2rem; color: #fff; border-color: #fff; & .${selectClasses.icon} { color: #fff; } & .${outlinedInputClasses.notchedOutl ...

The like button seems to be malfunctioning and I'm not sure what the issue is

I've added the ability for users to like my posts, but it's not working as intended. Here's the code snippet I used: models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(blank=Tru ...

What is the method for creating text that appears when the mouse is hovered over it?

My friend requested me to create a website for his YouTube channel with 4 links to different pages: Home, About Me, Merchandise, and Contact. He wants the text on these links to change color when hovered over, similar to terraria.org. I'm more profici ...

What is the best way to calculate the total of multiple columns using JavaScript and jQuery?

I am looking to modify my table that has two different columns in order to calculate the sum of both. Currently, I can only add up one column using JavaScript, and duplicating the JS code with different value names for the second column is not ideal. How c ...

Navigating back to the original page after venturing to a different one - react

In the header of each page, there is a 'Back' button that allows users to navigate back to the previous page. The function handleGoBack() is responsible for this: import React from 'react'; import { Button, Typography } from "@mate ...

Transforming a request from Angular to PHP through formatting

I am currently working on creating an add function for my Angular application that communicates with my PHP back-end. I am attempting to send data to the server using a transformationRequest, but I am unsure about the correct format that matches the $_POST ...

Utilize Angular's MatTableDataSource to filter data by comparing nested array values with an array selected from a multiselect

I am currently working with an Angular MatTableDataSource object that contains various properties as well as a nested array property consisting of IDs relevant to each row. Each element in the MatTableDataSource array has a structure similar to this: IMSI ...

Counting and Arranging Numerous Commitments in the World of Javascript

I’m faced with a challenging scenario that’s got me puzzled: -I’ve got an array of 10 objects, each with two properties: IDNum and imageURL. -Only 3 of these objects actually have their imageURL property set (at index positions [0, 4, 9]), and n ...

Getting User Input with HTML and JavaScript

Whenever a user enters their first and last name in the message box, I have 3 functions that return (a) Their names merged in array form and (b) Their names merged as an array of objects. The issue arises when I test it in Google Chrome; nothing appears wh ...

When a user enters their ID, I endeavor to generate a personalized visiting card using canvas

I am currently working on a project where I need to generate a personalized visiting card based on input data. The idea is to iterate over an object and retrieve the relevant information upon button click, displaying it on a canvas element. Initially, my p ...

Building a bespoke search input for the DataTables JQuery extension

As the title indicates, I am in the process of developing a custom search box for the DataTables JQuery plugin. The default options do not suit my needs, and configuring the DOM is also not ideal as I aim to integrate it within a table row for display purp ...

What is the process of generating a dynamic card/button element on an ASP.net webpage using information from the backend database?

I'm faced with a challenge of displaying employees' names and titles from a MSSQL Server database table on an ASP .NET webform as individual "card" objects. Currently, I am able to showcase a static number of records by using an asp button object ...

Collapse a previously used item when a new item is opened within Angular

I've managed to create a tree structure for a sideBar Menu using this code, and it's working well. However, what I'm trying to achieve is that when a menu with submenus is expanded and the user clicks on another parent menu, the expanded sub ...