Arranging string data in an array using JavaScript

I am faced with the task of merging and sorting two arrays containing string data:

var AA = ["~/80/Blue/1.png","~/80/Blue/2.png","~/80/Black/1.png","~/80/Black/2.png"];
var BB = ["~/81/Blue/1.png","~/81/Blue/2.png","~/81/Black/1.png","~/81/Black/2.png"];

To achieve this, I need to concatenate these arrays and sort them in a specific way:

 CC = ["~/80/Blue/1.png","~/81/Blue/1.png","~/80/Blue/2.png","~/81/Blue/2.png","~/80/Black/1.png","~/81/Black/1.png","~/80/Black/2.png","~/81/Black/2.png"];

The sorting criteria require pairs of array elements to have the same "color directory" and file name.

This is my attempted solution:

var CC = AA.concat(BB);
CC.sort (function(a,b) {
    var Mask = /\W\w+\W\d\Wpng/;
    var A =[];
    var B = [];
    var s1 = a.toLowerCase();
    var s2 = b.toLowerCase();
    for (var i=0; i<s1.length; i++){
      A.push(s1[i].match(Mask));
    }
    for (var i=0; i<s2.length; i++){
      B.push(s2[i].match(Mask));
    }
    for (var i=0; i<A.length; i++){
      for (var j=0; j<B.length; j++){
        if (A[i] < B[j]) {return -1;};
        if (A[i] > B[j]) {return 1;};
        else {return 0;}
        }
    }

Answer №1

To begin, combine the contents of both arrays and then arrange them in order using the Arrays.sort method. This can be achieved by specifying a sorting function as an argument.

var X = ["~/80/Blue/1.png","~/80/Blue/2.png","~/80/Black/1.png","~/80/Black/2.png"];
var Y = ["~/81/Blue/1.png","~/81/Blue/2.png","~/81/Black/1.png","~/81/Black/2.png"];
var Z = [];


var Z = X.concat(Y);

function customSort(a, b) {
   var A_colorFile = a.split('/').splice(2).join('/'); /* Blue/1.png */                
   var B_colorFile = b.split('/').splice(2).join('/');
   var A_directoryNum = a.split('/')[1]; /* 80 */
   var B_directoryNum = b.split('/')[1];
   if(A_colorFile !== B_colorFile){
      return A_colorFile < B_colorFile;
   } else{
      return A_directoryNum < B_directoryNum 
   }

}
Z.sort(customSort);

Answer №2

var X = ["~/70/Red/1.png","~/70/Red/2.png","~/70/Green/1.png","~/70/Green/2.png"];
var Y = ["~/71/Red/1.png","~/71/Red/2.png","~/71/Green/1.png","~/71/Green/2.png"];
var Z = [];

var largestArray = 0;

if (X.length > Y.length) {
 largestArray = X.length;
} else {
 largestArray = Y.length;
}

    for (var j = 0; j < largestArray; j++) {
      if (X[j]!==undefined) {
        Z.push(X[j]);
      };
      if (Y[j]!==undefined) {
        Z.push(Y[j]);
      };
    }

Does this meet your requirements?

Answer №3

Learn how to combine two arrays of the same length quickly.

var CombinedArray = ArrayA.reduce(function(result, value, i) {
    return result.concat(value, ArrayB[i]);
}, []);

Check out this helpful demo on JSFiddle: https://jsfiddle.net/uh0q2eqb/

Discover a method to organize and merge arrays with equal lengths based on directory and file names, then combine them together.

ArrayA.sort(comparator);
ArrayB.sort(comparator);

var CombinedArray = ArrayA.reduce(function(result, value, i) {
    return result.concat(value, ArrayB[i]);
}, []);

function comparator(a, b) {
  var A = a.split('/').splice(2).join('/');
  var B = b.split('/').splice(2).join('/');

  if (A > B) {
    return 1;
  } else if (A < B) {
    return -1;
  } else {
    return 0;
  }
}

Take a look at this demonstration on JSFiddle: https://jsfiddle.net/uh0q2eqb/1/

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

Improving JavaScript code for checking arrays and objects

When I receive data, it could be an array of objects or just a single object. I have written some code but I believe there is a way to improve it - make it more elegant, concise, and error-free. Here is the current code snippet: export const CalculateIt = ...

Looking for a fully customizable event and booking calendar?

Currently, I am searching for a unique event and booking calendar that provides the ability to customize each cell or day with our desired content. While most calendars only allow for inputting events as text, we require a solution that enables us to add ...

steps for integrating react-pannellum library into react/ionic

Trying to integrate a 3D panorama view into my React Ionic app, but encountering an error while attempting to install using either of the following commands: npm install --save react-pannellum npm install --save pannellum > npm WARN config global `-- ...

Every time I employ window.location, the Iframe becomes nested

I am experiencing an issue with my HTML structure: <html> <body> This is the container of the iframe <iframe src="/foo.html"> </iframe> </body> </html> (/foo.html) <html> <script type="text/javascript"> $( ...

Sending Unique Identifier to AJAX Script

As I delve into my inaugural AJAX script, coupled with PHP pages, the intricacies of AJAX are slowly revealing themselves to me. Being relatively new to Javascript, I have managed to successfully implement the script. The task at hand involves enhancing a ...

Utilize the nest function in D3 to organize flat data with a parent key into a hierarchical structure

I'm searching for an elegant and efficient solution to transform my input data into a hierarchical structure using d3.js nest operator. Here is an example of the input data: [ {id: 1, name: "Peter"}, {id: 2, name: "Paul", manager: 1}, {id: 3, name: " ...

Organizing lists with HTML unordered lists

Is it possible to sort list items by numbers within a strong tag using JavaScript code? The current code successfully sorts the numbers, but removes them from the div tag. (The JavaScript code used below is for sorting by Name and works properly when &apos ...

Conditional Rendering with Next.js for Smaller Displays

I've implemented a custom hook to dynamically render different elements on the webpage depending on the screen size. However, I've noticed that there is a slight delay during rendering due to the useEffect hook. The conditionally rendered element ...

$injector encountered a problem resolving the required dependency

Currently, I am attempting to adopt the LIFT protocol (Locate, Identify, Flat, Try(Dry)) for organizing my Angular projects. However, I am encountering difficulties in handling dependencies from other files. Here is the factory I have: (function () { ...

The correct approach to understanding if-else logic in conditional rendering with ReactJS

Recently, I started learning reactJS and encountered a bit of confusion while reading an if else statement in the conditional rendering that I had written. Here's the code snippet: this.setState({ loading: true }) axios('https:/ ...

Looking for nearby elements in 2-dimensional arrays and substituting them

Currently, I am in the process of creating a method to search a 2D array for a specific value and then replace all adjacent elements with that same value. I've been racking my brain over this problem for close to an hour, and I'm reaching out to ...

Spreading an object to remove a key may result in the returned value being

When creating a Radio Button object, each object in the array consists of {value: 1, text: 'Sometext'}. If a radio button is selected, 'selected: true' is added to that specific object and removed from the others. const onChoiceChange ...

collaborating on a multidimensional array

As a beginner in C++, I am facing some challenges with working on arrays for the first time. While I have a good grasp of general array concepts and how to initialize them, I am struggling when it comes to printing specific rows/columns from my 3D array. T ...

Display an icon button when a user edits the text in a text field, and make it disappear once clicked on

Figuring out how to incorporate a v-text-area with an added button (icon) that only appears when the text within the text area is edited, and disappears once it is clicked on, has proven to be quite challenging. Below is a simplified version of my code to ...

Sorting JsonNodes based on object values in Java can be achieved by following these steps

Is there a way to sort the product nodes in the given JsonNode response based on the 'cost' variable in either ascending or descending order? How can the value of the product node be modified to achieve this? JsonNode response: { "produ ...

Which option offers superior performance: using attributes through HTML or jQuery?

At times, I find myself needing to include special classes, divs, and attributes in my HTML code for jQuery scripts to function properly (the site's "no-JavaScript" version doesn't require these elements). You probably understand what I mean. I& ...

Techniques for passing PHP data to an input field with an AJAX call

Hello, I need some assistance with extracting a value from a PHP script using AJAX triggered by an onclick event. Within my HTML code, I have both a text field and a button: <button type="button" class="btn btn-primary" onclick="getid(this)">Genera ...

The function Class does not correctly return an array

For some reason, I am unable to retrieve the array properly from the function. Whenever I execute the script, it only displays 0, even though I have verified that the MySQL query has returned at least one row. I attempted using $_GLOBALS["FORUM_ANSWERS"][] ...

Just a simple canvas animation

My canvas animation consists of two rectangles moving in different directions, but I believe it can be simplified further. http://jsfiddle.net/tmyie/R5wx8/6/ var canvas = document.getElementById('canvas'), c = canvas.getContext('2d&apo ...

Effortlessly apply mapping, filtering, reducing, and more in JavaScript

Array#map and Array#filter both create a new array, effectively iterating over the original array each time. In languages like rust, python, java, c#, etc., such expression chains only iterate once, making them more efficient in certain cases. While this ...