Arrange the objects in the array according to the specified items that should come after

Consider the following data structure:

var set = [
    {
        "name":"alpha",
        "require":[]
    },
    {
        "name":"beta",
        "require":["echo"]
    },
    {
        "name":"charlie",
        "require":[]
    },
    {
        "name":"delta",
        "require":["charlie", "beta"]
    },
    {
        "name":"echo",
        "require":[]
    }
];

The task is to sort items based on multiple requirements, where items with dependencies should come after all the items they depend on. An example output for the given sample data would be:

alpha, charlie, echo, beta, delta

While the Array.sort method https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort can be used, understanding how to implement sorting based on multiple requirements may be challenging.

An attempt using a comparison function:

set.sort(function (a, b) {
    return a.name > b.require[0] ? 1 : -1;
});

-- Revised based on @hindmost's response --

However, the above approach may not always produce the desired result. Consider a new set of sample data:

var set = [
    {
        "name":"zzz",
        "require":["xxx"]
    },
    {
        "name":"xxx",
        "require":["yyy"]
    },
    {
        "name":"fff",
        "require":[]
    },
    {
        "name":"yyy",
        "require":["fff", "kkk"]
    },
    {
        "name":"kkk",
        "require":[]
    }
];

This input yields:

fff, kkk, xxx, zzz, yyy

Instead, the expected outcome is:

fff, kkk, yyy, xxx, zzz

To clarify, the sorting should not solely rely on alphabetical order or the length of the require array, but rather ensure that an item depending on others comes after its dependencies in the final sequence.

Answer №1

Give this a try:

set.sort(function (x, y) {
    return x.require.length === y.require.length ?
        (x.name < y.name ? -1 : 1) :
        (x.require.length < y.require.length ? -1 : 1);
});

Explanation:

Initially, the elements are compared based on the length of their require property and either returned as -1 (first is less than second) or 1 (first is greater than second). If the lengths of require are equal, then the comparison moves to the name property using a similar approach.

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

Exploring the global document object within Next.js

We have been working on a project using nextjs and are facing an issue with changing the styling of a button upon click. Despite using document.getElementById, we are unable to change the styling no matter what we try. pages/index.js function Index() { ...

Error occurred when attempting to save data to SQLite database, causing a critical issue

I am encountering an issue with saving data from nodes in an XML document that is loaded into my app using SimpleXML. The problem seems to be related to the SQL statement, as I am getting a fatal error. It's puzzling because the error mentions ' ...

Getting the value of an HTML list using JavaScript

I am attempting to extract values from an HTML list <li>. <ul> <li><a>Main Menu</a> <ul class="leftbutton" > <li value="List1"><a>Sampe 1</a></li> ...

Ways to send an argument and retrieve a response string from JavaScript to an ASP.NET page, then refresh the HTML content

I am facing a challenge with a dropdown list that triggers a javascript function (function typechanged(var)) when its value is changed. My task now is to send the var to the server, receive a menu based on the var string, and update the div where the dro ...

Steps to create a Runtime array and assign it a name from a predefined list

There's a list called list_1 = ["File_A","File_B","File_C","File_D"] I'm looking to execute a loop and create four arrays: File_A = np.array(0) File_B = np.array(0) File_C = np.array(0) File_D = np.arr ...

Ways to display pictures by invoking an API within the antd item list container

Upon page load, I am fetching images from a database using an API. Now, my goal is to display these images within a Modal in Antd. How can I accomplish this with the code snippet below? const MyVehiclePage = (props) => { useEffect(() => { co ...

Toggle the checkbox to either allow or prevent scrolling within the div element's content

I have successfully used jQuery to append content to a div on my website. In addition, I have applied CSS to the div with the following styling: #data { height: 700px; position: absolute; left: 0; right: 0; overflow-y: auto; vertical-align: b ...

DataTables.js, the powerful JavaScript library for creating interactive tables, and its compatible counterpart

I'm currently making some changes to a dynamic table that require enabling a vertical scroll bar. As a result, I need to implement this vertical scroll bar mechanism on an existing table. The code in our project utilizes dataTables.js version 1.5.2 ...

How to fetch a single document from a nested array using Mongoose

Currently, I am working on a MongoDB database using Mongoose in Node.js. The collection structure resembles the following: { cinema: 'xxx', account: 'yyy', media: { data: [{ id: 1, name: 'zzz& ...

Trigger the rowContextMenu in Tabulator Table by clicking a Button

Is there a way to add a button at the end of a table that, when clicked, opens a rowContextMenu below the button? Additionally, can the rowContextMenu pop up when right-clicking anywhere on the row? I have attempted some solutions without success. Here is ...

The SSE emitter sends out multiple signals, but occasionally the browser fails to receive them

When setting up an event emitter in a node.js/express application, I noticed that the events emitted are sometimes received multiple times by the front-end listener. Although I can confirm that emit is only called once, the same event gets emitted up to 4 ...

Is it possible to incorporate spread syntax(...) within a vue.js 2.x template?

Is it possible to utilize a similar structure in a vue.js template? <template> <vxe-table> <vxe-column v-for="options in someConsts" ...options width="160"> </vxe-column> </vxe-ta ...

Exploring the Combination of Conditional Rendering and Redux within the App.js File

Currently, I am in the process of setting up an authentication flow with Redux in my application. To control the display of either the app screen or the authentication screen, I have implemented conditional rendering in my App.js file. Here is the snippet ...

Ways to prevent images from vanishing when the mouse is swiftly glided over them

Within the code snippet, the icons are represented as images that tend to disappear when the mouse is swiftly moved over them. This issue arises due to the inclusion of a transition property that reduces the brightness of the image on hover. However, when ...

In React, I am unable to invoke a function that has been assigned to an element

import React from "react"; import shortid from "shortid"; export default class App extends React.Component { state = { items: [], text: "" }; handleTextChange = event => { this.setState({ text: event.target.value }); }; ...

There seems to be nothing in the request.body that was sent

I've encountered an issue with my code - whenever I use postman or cURL to send a post request, the body is empty. const express= require('express'); const app = express(); app.use(express.json()) app.post('/',(req,res)=>{ ...

Building an object in React using JavaScript: A step-by-step guide to including all necessary fields

I am working on a Sign-up page where I console log the input values from each field when the 'Sign Up' button is clicked. However, I want to combine these individual values into one object in the console. If anyone can provide assistance with thi ...

Top Mysql Row of the Week

Within a single table, I have IDs, PAGE_IDs, and DATES Whenever a page is accessed, the corresponding DATE and PAGE_ID are added to the table. I am attempting to determine and organize pages based on their popularity. The page table includes: IDs [PAGE ...

The art of posting with ExpressJS

I'm encountering a problem where the data submitted through a form to my POST route is not getting passed on to a database document, even though the redirection works fine. I'm unsure of how to troubleshoot this issue. blogpost-create.ejs &l ...

Sharing variables across multiple PHP files using $GLOBALS

I am working with a file named index.php, which generates a link to a page that I only want my user to access if a certain condition is met ($var == True). To achieve this, I aim to utilize the $GLOBALS array instead of the $_SESSION array since the latte ...