What is the best way to calculate the total of all files within a folder structure using JavaScript

Here is the array I'm working with:

Array (7812)
0 {foldername: "", amount_of_files: 12, children: 86}
1 {foldername: "/pm", amount_of_files: 3, children: 7}
2 {foldername: "/pm/css", amount_of_files: 1, children: 0}
3 {foldername: "/pm/js", amount_of_files: 1, children: 0}
4 {foldername: "/stohg", amount_of_files: 1, children: 2}
5 {foldername: "/stohg/de", amount_of_files: 6, children: 1}
6 {foldername: "/stohg/de/pictures", amount_of_files: 21, children: 1}
...

I am aiming to calculate the total number of files at the top level:

1 {foldername: "/pm", all_files: 5}
2 {foldername: "/stohg", all_files: 28}
...

This snippet looks like a step in the right direction:

array.filter(e => {
  const folders = e.foldername.split("/");
  if (folders.length === 1) {
    //maybe something with folders.reduce(); ?
  }
})

Answer №1

To simplify the process, you can create a basic regex and achieve the desired outcome using a single reduce method. In this scenario, we are specifically looking for the pattern /<word>.

var regEx = new RegExp(/^\/\w+$/, 'gm');

var folders = [{foldername: "", amount_of_files: 12, children: 86},
{foldername: "/pm", amount_of_files: 3, children: 7},
{foldername: "/pm/css", amount_of_files: 1, children: 0},
{foldername: "/pm/js", amount_of_files: 1, children: 0},
{foldername: "/stohg", amount_of_files: 1, children: 2},
{foldername: "/stohg/de", amount_of_files: 6, children: 1},
{foldername: "/stohg/de/pictures", amount_of_files: 21, children: 1}];

var sum = folders.reduce((acc, folder) => {
  if (regEx.test(folder.foldername)) {
    acc += folder.amount_of_files;
  }
  return acc;
}, 0);

console.log(sum);

Answer №2

Divide by the slash and combine them before adding up .amount_of_files The output format is slightly different from what was mentioned in your posts, but the result remains the same

<script>
function get_root_folder_path(path) {
    if( path === "" )
    return "/"; 
    var names = path.split("/");
  console.log(names);
    if( names.length >= 1 ) return "/" + names[1]; //note: names[0] === ""
  else return "INVALI3D";
}

var objs = [
{foldername: "", amount_of_files: 12, children: 86},
{foldername: "/pm", amount_of_files: 3, children: 7},
{foldername: "/pm/css", amount_of_files: 1, children: 0},
{foldername: "/pm/js", amount_of_files: 1, children: 0},
{foldername: "/stohg", amount_of_files: 1, children: 2},
{foldername: "/stohg/de", amount_of_files: 6, children: 1},
{foldername: "/stohg/de/pictures", amount_of_files: 21, children: 1},
];


// create an object to store your new root folder data
var root_folders = {};

for(var i = 0;i < objs.length;i ++) {
    var root_folder_path = get_root_folder_path(objs[i].foldername);
  if( root_folders[root_folder_path] === undefined )
    root_folders[root_folder_path] = {amount_of_files: objs[i].amount_of_files};
  else
    root_folders[root_folder_path].amount_of_files += objs[i].amount_of_files;
}

console.log(root_folders);

</script>

Outputs :

{
  /: {
    amount_of_files: 12
  },
  /pm: {
    amount_of_files: 5
  },
  /stohg: {
    amount_of_files: 28
  }
}

Jsfiddle: https://jsfiddle.net/3f7kgLvq/

Answer №3

After successfully resolving the issue on my own, I felt compelled to share the solution here in hopes of assisting anyone who may come across this post.

array.forEach(e => {
      const folders = e.foldername.split("/");
      const isRoot = folders.length === 2;
      if (isRoot) {
        result.push(e);
      } else {
        result.forEach((elem, index) => {
          if (elem.foldername === "/" + folders[1]) {
            result[index] = {...result[index], amount_of_files: elem.amount_of_files + e.amount_of_files}
          }
        })
      }
    });
    console.log(result);

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

Unexpected event triggering

I have come across a snippet of code that allows me to retrieve URL query strings var QueryURL = function () { var query_url = {}; var query = window.location.search.substring(1); var vars = query.split("&"); for (var i=0;i< ...

Having trouble applying CSS styles to an element using JavaScript

Hello, I have an unordered list with some list elements and I am trying to apply a CSS style to highlight the selected list element. However, the style is not taking effect as expected. function HighlightSelectedElement(ctrl) { var list = document.ge ...

Access the JSON data containing sub array values and showcase them on an HTML page by utilizing ngFor

Greetings! I am currently working on a web application where I need to showcase student data that is being received in JSON format. Below is the TypeScript code snippet that outlines the structure of the student data: export interface studentData{ ...

Having an issue with ng-model not functioning correctly in md-menu with AngularJS material

I'm currently using md-menu from Angular Material and I have integrated a search box with ng-model in the list. However, I am facing an issue where I cannot access ng-model because 'md-menu-content' is out of scope. Here is my code: <div ...

Removing users from a Socket.IO chat room using Node.js

I am facing an issue with removing users from Socket.IO when their browser is closed. The 'user' in the array 'users[]' is not getting removed or updated. Additionally, I would like to update the users on the client side as well. Can so ...

Transfer information from .gs (Google Apps Script) to a variable inside a <script> tag in an HTML document

[ {"id":1,"label":"Node 2"}, {"id":2,"label":"Node 3"}, {"id":3,"label":"Node 4"}, {"id":4,"label":"Node 5"} ] Hello there! The function getArray() in the code snippet above is returning the specified string ↑. I need help connecting this data w ...

Having trouble transitioning from Curl to Axios in Node.js? Encountering issues when trying to make a curl request using the provided certificates, resulting in ECONNRESET or

I've been struggling to make a successful curl request in Axios (Node.js) without any luck. A typical working curl request I use (can't provide exact details as the API is private) is like this: curl --cacert server.pem --cert client.pem:123pas ...

Attempting to use 'user' before it has been initialized is not allowed

I'm encountering a "Cannot access 'user' before initialization" error in my Mern development controller file for a signup function. Controller/user.js const user = require('../models/user') exports.signup = (req,res)=>{ cons ...

Having trouble getting Ajax post to function properly when using Contenteditable

After successfully implementing a <textarea> that can post content to the database without needing a button or page refresh, I decided to switch to an editable <div> for design reasons. I added the attribute contenteditable="true", but encounte ...

Issue with the gulp-babel plugin: Files within the Plugin/Preset should only export functions, not objects

I have started to integrate JavaScript 2015 (ES6) into my Ionic v1 app: package.json { "name": "test", "version": "1.0.0", "dependencies": { "@ionic-native/deeplinks": "^4.18.0", "cordova-android": "7.0.0", "cordova-android-support-gra ...

Cancelling measurements in Potree/three.js

Currently, I am utilizing Potree for the display of a large point cloud dataset, which can be found at https://github.com/potree/potree. I am attempting to initiate an area-measurement using Potree.MeasuringTool, which is typically stopped or accepted wit ...

Tips on using the ref attribute in Vue.js to focus on an input element

In my Vue.js component for 2FA, I have implemented the following structure: <template> <div :class="onwhite ? 'on-white' : ''"> <input :id="`n1`" ref="n1" v-model=&quo ...

Stop Ajax from activating jQuery function

Upon examining our Drupal site, we discovered a straightforward jQuery script that inserts a div class containing content: (function($) { Drupal.behaviors.myHelpText = { attach: function (context, settings) { //code begins //adjusting placeholder ...

How can you effectively transfer arguments from one component to another using router.push() in Vue.js?

I need help with implementing a feature where upon clicking the edit button in a row, all the details from that particular row should be passed to a form component. I want to populate the form fields with default values from the parameters provided. Can ...

Updating REST API: Sending a PUT request without requiring all data to be included in json format

I have a controller set up for updating user data. The controller can accept up to 4 values. I am wondering if it is possible to only update the name field when sending data to this route, leaving the rest of the fields unchanged (and not empty). Should ...

Finding an element that lacks both a class and an id, and is not consistently present - what's the trick?

Currently, I am faced with a predicament in my code where a <li> element only appears under specific conditions, making it difficult to apply positioning. This element lacks an id and class attribute, which prevents me from targeting it accurately us ...

Creating an index for a JSONB column in Postgres that contains an array of JSON values

In my postgres database, I have a table named "employee" with a JSON column called "mobile". This column stores an array of JSON values representing employee mobile numbers. e_id(integer) name(char) mobile(jsonb) 1 John [{\"mo ...

What steps can I take to deactivate input and stop it from being accessible on the browser?

insert image description Is there a method to block users from accessing disabled input fields in the browser? Any recommendations or solutions would be greatly appreciated. Vuejs is utilized within my project. Implementing this feature serves as a secu ...

Output the contents of a nested object

After setting up a variable containing music library data... var library = { tracks: { t01: { id: "t01", name: "Code Monkey", artist: "Jonathan Coulton", album: "Thing a Week Three" }, t02: { id: " ...

Vue component's data remains stagnant within created() hook

I'm currently working on transforming the API response to make it more suitable for constructing two tables. Despite adding debugging outputs within my function in created(), I am witnessing the desired output temporarily, but upon further examination ...