How do I sort items by hierarchy?

  • 0
    How to sort items by hierarchy (+ alphabet)?

    Example schemas

    There is an array of elements:
    const elements = [{
        id: 1,
        name: "JOBS",
        relations: [],
    }, {
        id: 2,
        name: "CUSTOMERS",
        relations: []
    }, {
        id: 3,
        name: "PRODUCTS",
        relations: [9],
    }, {
        id: 4,
        name: "PRODUCT_VIDEOS",
        relations: [3, 9],
    }, {
        id: 5,
        name: "USER_TOKENS",
        relations: [9]
    }, {
        id: 6,
        name: "USER_VIEWS",
        relations: [9]
    }, {
        id: 7,
        name: "PRODUCT_ACCESS",
        relations: [3]
    }, {
        id: 8,
        name: "PRODUCT_COMMENTS",
        relations: [3, 9]
    }, {
        id: 9,
        name: "USERS",
        relations: []
    }]


    The element has relations in which the id of the elements it depends on. How to sort items by hierarchy so that dependent items are only after the "parents"

    The result should be:
    CUSTOMERS
    JOBS
    USERS
    PRODUCTS
    PRODUCT_ACCESS
    PRODUCT_COMMENTS
    PRODUCT_VIDEOS
    USER_TOKENS
    USER_VIEWS
    JavaScript Caleb Walsh, Apr 21, 2020

  • 1 Answers
  • 0
    const sortedElements = [...elements].sort((a, b) =>
    a.relations.includes(b.id)
    ? 1
    : b.relations.includes(a.id)
    ? -1
    : a.name.localeCompare(b.name)
    );
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!