Arrange the items that are missing from Array B to be located at the bottom of Array A, organized in a file tree structure

I have two arrays containing different types of objects. Each object in the arrays has a title assigned to it. My goal is to compare these two arrays based on their titles and move any files that are not included in the bottom part of the fileStructure array to the end of the files array.

const files: FileType[] = [
    {
        info: { name: "fileThatsNotIncludedInArray2" },
        contents: [],
    },
    {
        info: { name: "fileThatsIncludedInArray2" },
        contents: [],
    },
    {
        info: { name: "fileThatsIncluded" },
        contents: [
            {
                info: { name: "chapterThatsNotIncludedInArray2" },
                contents: [],
            },
            {
                info: { name: "chapterThatsIncluded" },
                contents: [],
            },

        ],
    },
]

Another array I'm working with is:

const filesStructure: FilesStructure[] = [
    {
        title: "fileThatsIncludedInArray2",
        chapters: []
    },
    {
        title: "fileThatsIncluded",
        chapters:
            [
                {
                    title: "chapterThatsIncluded",
                    chapters: []
                },
            ]
    }
]

The desired outcome should look something like this:

const finalFiles: FileType[] = [
    {
        info: { name: "fileThatsIncludedInArray2" },
        contents: [],
    },
    {
        info: { name: "fileThatsIncluded" },
        contents: [
            {
                info: { name: "chapterThatsIncluded" },
                contents: [],
            },
            {
                info: { name: "chapterThatsNotIncludedInArray2" },
                contents: [],
            }
        ],
    },
    {
        info: { name: "fileThatsNotIncludedInArray2" },
        contents: [],
    },
]

Currently, my implementation only moves one item to the bottom and leaves out the rest. Here is the code snippet:

export function placeUnIncludedElementsAtTheEndOfTheSortedArray(
    sortedArray: FileType[],
    fileStructure: FilesStructure[],
): FileType[] {
    for (const sortedFile of sortedArray) {
        const findInd = fileStructure.findIndex((fr) => {
            return fr.title == sortedFile.info.name
        })

        if (findInd == -1) {
            sortedArray.push(sortedArray.splice(sortedArray.indexOf(sortedFile), 1)[0])
        }
    }

    return sortedArray
}

Answer №1

To organize the data properly, you should arrange it based on another array and prioritize the missing values by moving them to the end:

const sorted = ft.sort((a, b) => {
    const _a = fs.findIndex(s => s.title === a.info.name);
    const _b = fs.findIndex(s => s.title === b.info.name);
    return (_a == -1 || _b == -1) ? (_a == -1 ? 1 : -1) : (_a - _b);
});

A more detailed example is presented below:

function adjustDataStructure(ft: FileType[], fs: FilesStructure[]): FileType[] {
    // Rearrange based on another array and prioritize missing values
    const sorted = ft.sort((a, b) => {
        const _a = fs.findIndex(s => s.title === a.info.name);
        const _b = fs.findIndex(s => s.title === b.info.name);
        return (_a == -1 || _b == -1) ? (_a == -1 ? 1 : -1) : (_a - _b);
    });
    // Adding recursion 
    sorted.forEach(e => {
        const s = fs.find(s => s.title === e.info.name);
        if (s) e.contents = adjustDataStructure(e.contents, s.chapters);
    })

    return sorted;
}

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

The template in AngularJS route fails to display

I am currently facing an issue with loading multiple pages using AngularJS $routeProvider and two controllers. Whenever I click on a link from the first partial to go to the second one, the second partial fails to render properly, displaying only template ...

Dispatching actions in `componentDidMount` is restricted in Redux

Update at the bottom of post I've created a React container component called AppContainer, which checks if the user is authenticated. If the user is authenticated, it renders the app's routes, header, and content. If not, it displays a Login com ...

Wrap it in a ReactJS container tag

Today I encountered a frustrating issue while diving into ReactJS. I'm excited to learn by getting my hands dirty, but unfortunately, I keep running into this error: Adjacent JSX elements must be wrapped in an enclosing tag (47:14) And here's t ...

Is it possible to use Firebase auth.user in order to retrieve the signed-in user directly?

As I develop a webapp with NextJS v13.4 and firebase as my backend using the firebase web modular api, I came across a statement in the documentation: "The recommended way to get the current user is by setting an observer on the Auth object." ...

Tips for showing solely the current page number within angular pagination

HTML : <!-- pagination controls --> <div class="pagination-container"> <pagination-controls (pageChange)="onPageChange($event)" [maxSize]="1" [id]="config.id" [directionLinks]="true">< ...

Steps to duplicate a Select input and attach it to a div using Jquery

Recently, I was working on a Select input with the name "item" as an example. <select name="item"> <option value="1">1</option> <option value="2" selected="selected">2</option> <option value="3">3</option> <opt ...

Wait to fade in until the fade out process is completely finished

When I click on a button, the old box fades out and the new box fades in. However, I want to ensure that the .fadeIn() only happens once the .fadeOut() is complete. This will prevent two containers from being displayed simultaneously. Any suggestions on ...

Error encountered in Typescript: The property 'prevUrl' is expected to be present in the props object, but it appears to be missing

When trying to access the props.prevUrl property, the following error is encountered: Property 'prevUrl' does not exist on type '{ nextUrl: string; } | { prevUrl: string; nextUrl: string; } | { prevUrl: string; confirm: () => void; }&apos ...

Tips for patiently anticipating the outcome of asynchronous procedures?

I have the given code snippet: async function seedDb() { let users: Array<Users> = [ ... ]; applications.map(async (user) => await prisma.user.upsert( { create: user, update: {}, where: { id: user.id } })); } async function main() { aw ...

The HTML page is displaying the Express.js GET request

As a beginner in express.js, I'm encountering an issue where data sent to the client is displayed directly in the browser instead of appearing as a preview. Can someone please review my code and help me identify what I'm doing wrong? app.use(cors ...

The power of the V8 JavaScript engine: Understanding v8::Arguments and the versatility of function

I have created a Node.js addon that wraps a C++ standard library element std::map<T1,T2>. The goal is to expose this map as a module with two primary functions: Set for adding new key-value pairs and Get for retrieving values by key. I want to create ...

"iOS users have reported that notifications from Firebase have mysteriously ceased to

Yesterday evening, I was experimenting with Push Notifications from Firebase on my iOS application and everything was functioning correctly. I successfully sent a notification from a Cloud Function to a specific FCM token. However, this morning, notificat ...

The parameters remain consistent across all Angular directives

I have created a directive called 'filterComponent' with the following code: app.directive('filterComponent', function() { return { restrict: 'E', templateUrl: 'filter-component.html', link: function ...

What are the steps to extract information from an observable?

Having trouble retrieving data from a request? I've encountered an issue where the data retrieved inside .subscribe in an observable function is returning as undefined when trying to access it outside the function. It's quite frustrating! Here i ...

Having trouble navigating typescript's "import" syntax in conjunction with compiler options like module and choosing between esnext and commonjs?

I am facing an issue with my typescript project that includes mocha tests. Here is a snippet of how the tests start: import { assert } from "chai"; import "@material/mwc-ripple"; //I need to test a script that uses this describe("simple test", () => { ...

Creating a dynamically generated JavaScript array using the JSON format

I am in need of creating an array of JSON data. Here is an example: [ { "DataCategoryGroupId": "22222222-2222-2222-2222-222222222222", "AnswerOptionIds": [ "76e32546-0e26-4037-b253-823b21f6eefb", "10d02a3e-9f9f- ...

Swapping out a code snippet within an HTML document using JavaScript

As a new member of this community, I present to you my very first problem that needs solving. It might be a piece of cake for some of you, but for me, it's proving to be quite tricky. The task at hand involves replacing or removing a string to make ev ...

Is there a way to prompt WebAPI to receive a complicated object as its argument for a DELETE HTTP request without relying on C# attributes?

Currently, my server is utilizing C#/WebAPI while the client side is using AngularJS. I am faced with a dilemma when it comes to formatting an HTTP DELETE request without specifying attributes in C#. Specifically, I am struggling with how to handle a meth ...

What is the best method for retrieving the character's ID from within an object?

Exploring my collection of movies, I discovered that each movie contains an array of characters. My goal is to display specific information about each character (such as their name and age) when clicked on, requiring me to obtain the id of each character. ...

Accessing JSON data model from Ember route or controller

Exploring the capabilities of Ember.js Is it possible to expose my data model as JSON through a route or controller? The object saved in the store looks like this: this.store.createRecord('Person', { id: 1, name: this.get('name'), ...