Recursively sort a specific file within the top-level directory

Can anyone help me figure out how to identify the dist.xml files located in the highest directory?

For example, I have this list of directories:

/opt/pictures/dist.xml
/opt/docs_old/dist.xml
/opt/public/dist.xml
/opt/documents/server/dist.xml
/opt/documents/dist.xml
/opt/documents/web/dist.xml
/opt/documents/class/dist.xml
/opt/documents/lessons/1/dist.xml
/opt/documents/lessons/2/dist.xml
/opt/documents/lessons/3/dist.xml
/opt/documents/lessons/4/dist.xml
/opt/documents/lessons/5/dist.xml
/opt/music/service/day/dist.xml
/opt/music/service/week/dist.xml
/opt/music/service/month/dist.xml
/opt/music/service/month/1/dist.xml
/opt/music/service/month/2/dist.xml

I would like the output to display only the topmost directory paths that contain a dist.xml file:

/opt/pictures/dist.xml
/opt/docs_old/dist.xml
/opt/public/dist.xml
/opt/documents/dist.xml
/opt/music/service/day/dist.xml
/opt/music/service/week/dist.xml
/opt/music/service/month/dist.xml

I'm attempting to accomplish this using JavaScript. My initial thought was to perform a simple sort.

Answer №1

To organize these strings, you can arrange them based on the number of slashes and then alphabetically by character while also filtering out duplicate paths.

var data = ['/opt/pictures/dist.xml', '/opt/docs_old/dist.xml', '/opt/public/dist.xml', '/opt/documents/server/dist.xml', '/opt/documents/dist.xml', '/opt/documents/web/dist.xml', '/opt/documents/class/dist.xml', '/opt/documents/lessons/1/dist.xml', '/opt/documents/lessons/2/dist.xml', '/opt/documents/lessons/3/dist.xml', '/opt/documents/lessons/4/dist.xml', '/opt/documents/lessons/5/dist.xml', '/opt/music/service/day/dist.xml', '/opt/music/service/week/dist.xml', '/opt/music/service/month/dist.xml', '/opt/music/service/month/1/dist.xml', '/opt/music/service/month/2/dist.xml'],
    result = data
        .sort((a, b) =>
            a.replace(/[^\/]+/g, '').length - b.replace(/[^\/]+/g, '').length ||
            a > b || -(a < b)
        )
        .filter(
            (seen => s =>
                (parts =>
                    !parts.some((_, i, p) => seen.has(p.slice(0, i + 1).join('/'))) && 
                    seen.add(parts.join('/'))
                )
                (s.split('/').slice(0, -1))
            )
            (new Set)
        );

console.log(result);

Answer №2

No need for sorting here. First, insert all paths into a Set, then after that, use the filter method on the array to remove paths with ancestors present in the set.

var paths = ['/opt/pictures/dist.xml', '/opt/docs_old/dist.xml', '/opt/public/dist.xml', '/opt/documents/server/dist.xml', '/opt/documents/dist.xml', '/opt/documents/web/dist.xml', '/opt/documents/class/dist.xml', '/opt/documents/lessons/1/dist.xml', '/opt/documents/lessons/2/dist.xml', '/opt/documents/lessons/3/dist.xml', '/opt/documents/lessons/4/dist.xml', '/opt/documents/lessons/5/dist.xml', '/opt/music/service/day/dist.xml', '/opt/music/service/week/dist.xml', '/opt/music/service/month/dist.xml', '/opt/music/service/month/1/dist.xml', '/opt/music/service/month/2/dist.xml'];

const allPaths = new Set(paths);
const filteredPaths = paths.filter(path => {
    const parts = path.split("/");
    const filename = parts.pop();
    return !Array.from({length: parts.length}, (_, i) => i).some(i =>
        allPaths.has(parts.slice(0, i).concat([filename]).join("/"))
    );
});
console.log(filteredPaths);

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

Explore the jQuery feature that allows you to hover over text

I'm facing an issue that has got me a bit stuck on how to resolve it. Currently, when hovering over this specific image, the opacity decreases (exposing a background color) and text appears. However, I want this effect to persist even when hovering o ...

Angular UI-router allowing links to direct to different sections of the same domain but outside of the app

I am currently working on implementing ui-router in my Angular application. The base URL I am using is "/segments" and I have defined it using the base tag. <base href="/segments" /> Below is my routing configuration: var base = "/segments" $sta ...

Transform the collection of nested objects into an array of objects with identical key-value pairs and then output the result after each iteration

My goal is to transform an object with objects inside into an array of objects. The initial data looks like this: "data" :{ "tDetails": { "tName": "Limited", "tPay": "xyz" } ...

Within Codesandbox using Vue, the error message 'The property or method "children" is not defined in the instance, but is referenced during rendering.' appeared

Currently, I am in the process of creating a versatile State Manager that can seamlessly integrate with various Frontend Frameworks, including Vue. In order to showcase how the State Manager can be utilized within Vue, I have set up a simple codesandbox de ...

Transforming Poloniex API Callback JSON into a compatible format for Highcharts.Stockchart

I am currently working on a project that involves retrieving JSON data from Poloniex's public API method (specifically the returnChartData method) to generate a graph using Highchart Stockchart. The graph would display the historical performance of va ...

What is the method for including an input field beside the y-axis label in Chart.js?

I'm struggling to implement a live poll using Chart.js where users can select their option by checking a checkbox next to the y-axis label. My initial attempt was unsuccessful as placing the input boxes outside of the canvas led to alignment issues wi ...

Problem encountered in NextJS/ReactJS when attempting to dynamically load a new component by clicking a button within the current component

In my NextJS project, I am working with 3 components named "Sidebar", "Woven", and "ToolsPage". Below are the respective codes for each: ToolsPage Component: "use client" import Woven from './components/weaved'; import Sidebar from &ap ...

Modifying CSS styles in JavaScript based on the user's browser restrictions

My CSS style looks like this: button.gradient { background: -moz-linear-gradient(top, #00ff00 0%, #009900 50%, #00dd00); background: -webkit-gradient(linear, left top, left bottom, from(#00ff00), color-stop(0.50, #009900), to(#00dd00) ...

Utilizing the Global Module in NestJs: A Step-by-Step Guide

My current project is built using NestJS for the back-end. I recently discovered that in NestJS, we have the ability to create Global Modules. Here is an example of how my global module is structured: //Module import {Global, Module} from "@nestjs/commo ...

Sorting information in the React Native Section List

Working with React Native's SectionList and filtering data: data: [ { title: "Asia", data: ["Taj Mahal", "Great Wall of China", "Petra"] }, { title: "South America", data: ["Machu Picchu", "Christ the Redeemer", "C ...

Transforming the playbackRate property of a web audio-enabled audio element

I recently experimented with integrating an audio element into the web audio API using createMediaElementSource and achieved success. However, I encountered an issue when attempting to change the playback rate of the audio tag. Despite trying multiple appr ...

Having trouble launching the Socket.io Chat Demo? Encounter an issue with the error message at ..//

Hello, I am a novice in the world of programming and recently attempted to run the socket.io chat demo. Unfortunately, I encountered an error message at line 5 stating that it cannot find ('../..'). Can someone please shed some light on why this ...

Is the only hash in the anchor tag referring to a link?

In the new project I'm diving into, my focus has shifted from backend development to web-related tasks. While exploring the HTML codebase, I noticed a recurring pattern: <a href='#'>some link</a> Subsequently, JavaScript is lin ...

Discovering the worth of an array property in JavaScript

I have a custom script that generates and outputs a JSON formatted object: function test() { autoscaling.describeAutoScalingGroups(params, function(err, data) { if (err) console.log(err, err.stack); // an error occurred else console.lo ...

How can the top height of a jquery dialog be reduced?

Just starting out with jquery, I've got a dialog box and I'm looking to decrease the height of this red image: https://i.sstatic.net/BuyQL.png Is there a way to do it? I've already made changes in the jquery-ui.css code, like so: .ui-dia ...

Using TypeORM in Javascript to create routes efficiently

After examining the TypeORM websites examples, I noticed that some of them demonstrate routing usage using TypeScript. Given that TypeORM has the capability to use JavaScript instead of TypeScript, I am seeking guidance on how to implement Express routing ...

Grab every piece of JavaScript code and styling from the HTML document and transfer it into a textarea field

Below is my code that extracts the JavaScript like this: src="assets/js/jquery.min.js" src="assets/smooth-scroll/smooth-scroll.js" I want it to look like this: (I believe my regex is incorrect): <script src="assets/js/jquery.min.js"></script> ...

"Error: Discord Js encounters an issue trying to access the titles property of an

Having trouble with a random number generator in my discord bot. Whenever someone enters +nhr, it may work or display an error message in the console: TypeError: Cannot read property 'titles' of undefined and Unhandled promise rejection. Thi ...

Sending an array from PHP to Javascript using PHP can be done by creating the array

Looking for assistance on passing an array of values from PHP and retrieving it using AJAX. I've only been able to pass a single value so far, and I'm unsure how to handle arrays on the AJAX side. Here's my PHP code: $success[]; $timeout[] ...

The IMG onclick event for LinkModalDialog does not function properly on Mozilla browsers

I am currently utilizing the following function: function OpenLinkModal(obj){ var arr=showModalDialog("../../files/list_simple.asp","","dialogHeight: 600px; dialogWidth: 450px; edge: Raised; center: Yes; resizable: Yes; status: Yes; scroll: Yes; help ...