Instructions for arranging a collection of file size strings in descending order based on their values

I am currently working on sorting a list or array of file size strings in an intelligent manner, either in ascending or descending order. The string format consists of numbers (with or without decimals) followed by whitespace and then the unit.

For instance - ["5.1 GB", "19934563 B", "224 kB", "0.55 GB", "0.04 kB", "0.02 TB", "2.4 MB",], the expected result should be ["0.02 TB", "5.1 GB", "0.55 GB", "19934563 B", "2.4 MB", "224 kB", "0.04 kB"]

So far, this is my progress:

  
  if (!fileSizes.length) return "Please enter a list to be sorted";
  else {
    //Checking the input format of strings
    let validFormat = fileSizes.map((file) => validateFile(file));
    if (validFormat.includes(false)) return "Invalid input format";
    else {
      let myfiles = reOrderFormat(fileSizes);
      if (descending === true) {
        sorter = MySort("TGMkB");
        let mysortedFiles = myfiles.sort(sorter);
        
        let result = reOrderFormat(mysortedFiles);
        return result;
      } else {
        sorter = MySort("BkMGT");
        let mysortedFiles = myfiles.sort(sorter);
        
        let result = reOrderFormat(mysortedFiles);
        return result;
      }
    }
  }
}

//Helper Functions for validating input format
function validateFile(str) {
  let regEx = /^(-?\d*(\.\d+)?)\s((T|G|M|k)*B)$/;
  let valid = regEx.test(str);
  return valid;
}

function validateList(arr) {
  let validArray = arr.map((fileSiz) => validateFile(fileSiz));
  return arr;
}

//Helper functions for sorting and reordering input format
function reOrderFormat(arr) {
  let reOrdered = [];
  arr.map((file) => {
    let out = file.split(" ");
    let first = out[1];
    let second = out[0];
    let newOrder = first + " " + second;
    reOrdered.push(newOrder);
  });
  return reOrdered;
}

//Custom sorter function
function MySort(alphabet) {
  return function (a, b) {
    var index_a = alphabet.indexOf(a[0]),
      index_b = alphabet.indexOf(b[0]);

    if (index_a === index_b) {
     
      if (a < b) {
        return -1;
      } else if (a > b) {
        return 1;
      }
      return 0;
    } else {
      return index_a - index_b;
    }
  };
}

sort(
  ["5.1 GB", "19934563 B", "224 kB", "0.55 GB", "0.04 kB", "0.02 TB", "2.4 MB"],
  true
);

The current implementation does not handle repeated units properly and may mix up long figures in bytes. I am looking for assistance in coding a more efficient solution.

Please provide any insights or suggestions you may have. Thank you.

Answer №1

Your issue has been successfully resolved using a unique method called sorting by comparator. I created a global array:

let sizes = ["B", "kB", "MB", "GB", "TB"];
, arranged in size order. Assuming your main function is named 'main' as shown below, upon utilizing the function sortSizes on the arr variable, the resulting array should match the expected array:

function main() {
  let arr = ["5.1 GB", "19934563 B", "224 kB", "0.55 GB", "0.04 kB", "0.02 TB", "2.4 MB"];
  let expected = ["0.02 TB", "5.1 GB", "0.55 GB", "19934563 B", "2.4 MB", "224 kB", "0.04 kB"];
  let new_arr = sortSizes(arr);
  console.log(new_arr);
  console.log(expected);
}

Both console logs are expected to display the same sorted array.

// Global Array
let sizes = ["B", "kB", "MB", "GB", "TB"];

function sortSizes(arr) {

  // Sort by Comparator
  arr.sort(function(x, y) {
    var x_res = x.split(" "), y_res = y.split(" ");
    var x_value = x_res[0], x_unit = x_res[1];
    var y_value = y_res[0], y_unit = y_res[1];

    let amount = casting(x_unit, y_unit, x_value);

    if(amount < y_value) {
      return -1;
    } else if(x_value > y_value) {
      return 1;
    } else {
      return 0;
    }
  });

  return arr.reverse();
}

The casting function takes two units and an amount, then returns the amount after converting from the first unit to the second, e.g., from 5.1 GB to B should yield: 5476083302.4 B.

function casting(unit_from, unit_to, amount) {
  var i = sizes.indexOf(unit_from);
  var j = sizes.indexOf(unit_to);
  var r;
  if(i < j) {
    r = j - i;
  } else {
    r = j - i;
  }

  var i = 0;
  if(r < 0) {
    r *= (-1);
    while(i < r) {
      amount *= 1024;
      i++;
    }
  } else {
    while(i < r) {
      amount /= 1024;
      i++;
    }
  }
  
  return amount;
}

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

Using Regular Expressions in JavaScript for Filtering with Angular.js

I am looking to create a custom filter in Angular.js. When an object has a name == null, and I add "u" to the filter->, it results in the return of the object where name == null because re.test(null)=true. However, other characters are returning false. ...

A guide to extracting value from an input field with the power of JavaScript

I am currently facing an issue retrieving values from input fields. Some of these input fields are a result of a calculation process, such as #t1_potensi and #t2_potensi, while #aliran is the outcome of the overall calculation process. Below is my HTML co ...

POST method error 400 encountered

Whenever I execute my ajax jquery function, I encounter a 400 error Here is my code. All Postman tests pass successfully, but when the web app runs, it fails. I'm not sure if it's a coding issue or something related to HTML5. Can anyone offer as ...

Duplicating Javascript object containing private member

I've searched high and low without finding a solution. Why is it so difficult to clone a javascript object with private members without causing them to become quantum entangled? Take a look at this code... It's a simple private property with get ...

Encountering a pair of issues within a C program

Below is the code I have composed along with an explanation of the issues I am facing. #include <stdio.h> #include <string.h> //defining an array int arrayElements(array) { for (int i = 0; i <= strlen(array); i++) { printf( ...

Locating a specific item using its individual ID within Firebase

One thing that's often overlooked in Firebase tutorials is how to retrieve objects based on their unique IDs. The push() method generates these unique IDs automatically, but the question remains: how do we access the specific object associated with an ...

Enhancing particular components within C array

I'm struggling to visualize the process for handling some of my code. Within my C program, I need to compare each element of an array of structs (referred to as arr_person[i].name) to a user's input in order to check for matches. For example, if ...

How to manipulate arrays containing characters in the C programming language

Recently, I've been working with a data structure like this: struct coordinates{ struct coord coord_board[8][8]; }; To initialize it, I used the following code: coordBoard = malloc(sizeof(struct coordinates)); for (col = 'a'; col < ...

How to utilize ngFor for multiple inputs in Angular 4

Apologies for my poor English, I'll do my best to explain my issue. Here's the problem: I'm using ngFor on an Input element, but when I enter data, it gets repeated in all the fields and I can't figure out why. <div *ngFor=" ...

Can a website built with VueJs be successfully deployed on Wordpress for a client?

Is it possible to launch a VueJs only client website on WordPress without using templates? I'm curious if this approach is feasible. If so, do you have any recommended tutorials for achieving this? If not, what alternative solution would you suggest? ...

What is the process for combining an array that represents an integer with varying numbers of digits?

Is it possible to add two integers with different number of digits using an array in a way that does not trigger an out of bounds exception? Consider, for example, adding 500 + 99 where each digit is represented as an element within the array. The follow ...

IE11 displays a white screen when in fullscreen mode

I am currently working on a three.js webGL application and attempting to make it go fullscreen using the following code: launchFullscreen(document.documentElement); function launchFullscreen(element) { if(element.requestFullscreen) { ele ...

What is the reason behind a number having its final two digits transformed into zeros?

Query Hello, I was coding my discord bot and storing user IDs in a database. I plan to use these IDs to ping or assign roles to users. Issue However, I encountered a problem where the IDs in the database are being altered. For example, from 5336929053871 ...

Organizing an array in PHP without using the ksort function

I am attempting to manually organize a PHP array without relying on ksort. Here is my current code: function my_ksort(&$arg){ foreach($arg as $key1 => $value1){ foreach($arg as $key2 => $value2){ if($key1 > $key2){ ...

jQuery Ajax error 403 (unlike XMLHttpRequest)

Recently, I encountered an issue with two Ajax calls in my code. One of the calls was implemented using XMLHttpRequest and the other one using jQuery. Surprisingly, the first call completed successfully without any errors. However, the second call, which s ...

Guide on altering the Class with jquery

Here is My jQuery Code: $('a#cusine1').on('click', function(){ $('div#product-list').html("LOADING..........").show(); $(".ccid").addClass("0"); document.getElementById("ccid1").className="acti ...

Utilize AngularFire to generate a new User and invoke the factory function to showcase notifications

I recently started working with AngularJS and wanted to integrate it with AngularFire/Firebase for storing project data. I created a factory that manages notifications to be displayed in a centralized location. Here is the structure of my factory: myApp.f ...

What is the procedure for canceling a readline interface inquiry?

TL;DR I encountered an issue with the native Node.js Readline module. Once a question is asked using rl.question(query[, options], callback), it seems there is no straightforward way to cancel the question if it's pending an answer. Is there a clean ...

The style of react-router links remains unvisited

Currently working on a small website using React Router, I've encountered an issue where only the homepage link receives the visited styles. The other links do not display the visited style, even after being visited. Check out the code here Here is ...

Why is the object not being initialized in a new API call while the string variable is successfully initialized?

There seems to be a basic issue that I am missing, as to why this is happening. GET: example.com/users //returns all data GET: example.com/users?status=1 //returns data with status = 1 GET: example.com/users // this does not work returns the same dat ...