Is there a way to arrange an array based on the initial value?

In my array, I have a mixture of strings and arrays. Each string corresponds to the array next to it. For example, the string 789 is associated with the array ['111A', '222B', '333C']. My goal is to sort based on the strings while maintaining the connection to the relevant array.

I attempted to use the sort() method, which works fine when dealing only with strings in the array. However, as soon as I introduce arrays, the default sorting behavior returns.

let myArray = [
  '789', 
  ['111A','222B','333C'], 
  '456',
  ['444E','555F','666G'], 
  '123',
  ['777H','888I','999J']
]

myArray.sort(function(a,b){
return a - b
})

Ultimately, I want the final data to be sorted like this:

['123', ['777H', '888I','999J'],
'456', ['444E', '555F', '666G'],
'789', ['111A', '222B', '333C']]

Answer №1

If you want to group pairs of elements in an array, sort them, and then flatten the array, you can use this approach.

var array = ['789', ['111', '222', '333'], '456', ['444', '555', '666'], '123', ['777', '888', '999']],
    result = array
        .reduce((r, v, i) => {
            if (i % 2) r[r.length - 1].push(v);
            else  r.push([v]);
            return r;
        }, [])
        .sort(([a], [b]) => a - b)
        .reduce((r, a) => r.concat(a), []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To keep the 2 elements together for each String found, consider creating an array and then sorting by the strings while applying a concat function to rearrange the array in the desired order:

let myArray = [
      '789',
      ['111', '222', '333'],
      '456',
      ['444', '555', '666'],
      '123',
      ['777', '888', '999'],
];
    
const orderMyArrayByTheStrings = (myArray) => {
    
  const myArrayWithArrays = myArray
        .reduce((acc, el, index, array) => {
          if (!(el instanceof Array)) {
            return acc.push([el, array[index + 1]]) && acc;
          } else {
            return acc;
          }
        }, [])

  const myArraySortedByStrings = myArrayWithArrays.sort((a, b) => {
          return a[0] - b[0];
        })
    
  return [].concat.apply([], myArraySortedByStrings)
    
}
    
console.log(orderMyArrayByTheStrings(myArray))

Answer №3

If you want to customize the sorting function, you can modify it to change the type of items - like using toString().

let myArray = [
    '789', 
    ['111','222','333'], 
    '456',
    ['444','555','666'], 
    '123',
    ['777','888','999']
];
myArray.sort((left,right)=>{
    if(left.toString() < right.toString()) {
        return -1;
    } else if(left.toString() > right.toString()) {
        return 1;
    } else {
        return 0;
    }
});

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 supertest request body cannot be found

Testing my express server POST endpoint using supertest has been a challenge for me. Although everything works perfectly in postman, I encountered an issue when trying to pass body parameters into the test. It seems like the body parameters are not being p ...

Remove files from a folder and eliminate references in a separate list in a different database

I have two collections, one for reviews and one for users. In the users collection, there is an array called reviews, which contains the _ids of the reviews from the reviews collection. Sometimes, I find myself deleting reviews from the reviews collection ...

Injecting multiple instances of an abstract service in Angular can be achieved using the following techniques

I am fairly new to Angular and currently trying to make sense of the code written by a more experienced developer. Please excuse me if I'm not adhering to the standard communication practices and vocabulary. There is an abstract class called abstract ...

The invocation of res.json() results in the generation of CastError

An issue occurs with CastError when using res.json() with an argument: CastError: Failed to cast value "undefined" to ObjectId for the "_id" field in the "Post" model Interestingly, using just res.status(), res.sendStatus(), or res.json() without argument ...

What could be the reason for data-id coming back as undefined?

I'm having trouble figuring out why the code below isn't working for me. The console is showing 'undefined' for data-id. href='#detailsModal' class='btn btn-info btn-xs' data-toggle='modal' data-id='x ...

Combining click and change events in JQuery

Is it possible to listen for both click and change events in one code block? $(document).on("click", "button.options_buy",function(event) { // code for click event } $(document).on("change", "select.options_buy",function(event) { // code for chan ...

Utilizing modular structure for efficient jQuery AJAX request

Seeking guidance on optimizing multiple GET ajax calls, where each function contains repeated $.ajax({}) code lines. Is it feasible to create a single $.ajax({}) function and utilize it in all functions instead of duplicating the code? Perhaps something ...

Discover the method for populating Select2 dropdown with AJAX-loaded results

I have a basic select2 box that displays a dropdown menu. Now, I am looking for the most effective method to refresh the dropdown menu every time the select menu is opened by using the results of an AJAX call. The ajax call will yield: <option value=1 ...

Problem encountered when trying to use a single button for both opening and closing functionality in JQuery

Hello everyone, I'm currently working on creating a button that toggles between opening and closing. When clicked the first time, it should open, and when clicked the second time, it should close and reset. Here is the code I've written so far. ...

When I attempt to incorporate multiple sliders on a single page, I encounter difficulties in determining the accurate stopping position if the number of slides varies

I am having trouble setting the correct stop position for sliders with different numbers of slides on a page. When I have the same number of slides in each slider, everything works fine. However, I need to have a different number of slides in each slider ...

Try utilizing querySelectorAll() to target the second item in the list

As I delve into the world of HTML and JS, I came across the document.querySelectorAll() API. It allows me to target document.querySelectorAll('#example-container li:first-child'); to select the first child within a list with the ID 'exampl ...

What is the reason behind this Uncaught TypeError that is happening?

After converting my questionnaire to a PHP file and adding a validation script, I encountered an error: Uncaught TypeError: Cannot set property 'onClick' of null The error is pointing me to line 163 in my JavaScript file, where the function f ...

Eliminate any duplicated items from the array located at the end

I have a set of data that I need to organize into arrays of two. This is how the arrays look: $array1 = array(30,17,12,6,89,23,45,45,45); $array2 = array(30,17,12,6,89,23,45,45,45,45); If the last element of $array1 matches the last element of $array2, ...

I am encountering a "TypeError: topics.forEach is not a function" error when attempting to retrieve metadata for topics using my kafkajs client in Node.js/express.js. Can anyone help me understand why

I am attempting to retrieve the metadata of my Kafka brokers' topics using the kafkajs admin client within my Node.js + express.js server. Here is the content of my index.js file, serving as the main entrypoint for npm: 'use strict'; cons ...

Gulp- Ensuring the latest versions of your javascript files

I have implemented bundling and minification for my JavaScript files using gulp. What I am aiming to achieve is that whenever I make a change in any of my files and run gulp, a new bundled and minified file with a version number is generated. For example: ...

What is the best way to display a component based on the route using GatsbyJS?

Currently working with GatsbyJS and attempting to dynamically render different header components based on the URL route. For instance: mydomain.com/ should display HeaderLanding mydomain.com/blog should display HeaderMain Seeking guidance on how to imp ...

Having trouble with object initialization in a jQuery GET request?

Looking to create an HTML button using jQuery that, upon clicking the chart button, will retrieve values from specified text inputs. These values will then be used to construct a JSON object which will subsequently be included in a GET request. $(".chart" ...

Steps to finish (refresh) a mongoDB record

Currently, I am dealing with the following scenario: An API request from one service is creating multiple MongoDB documents in a single collection. For example: [ {_id: 1, test1: 2, test: 3}, {_id: 2, test1: 3, test: 4} ] Subsequently, a second service ...

Unable to locate module post npm installation

My Node.js application is running on an Ubuntu server hosted on Microsoft Azure. The package.json file for my project includes various dependencies required for the app to function. { "author" : "Coop", "name" : "app-framework", "main" ...

Performance comparison between Javascript Object and Map/Set for key lookup

I decided to experiment with the performance of JavaScript Object, Map, and Set when it comes to accessing keys. I tested the following three code snippets on JSBEN.CH. Objects const object = {}; for (let i = 0; i < 10000; ++i) { object[`key_${i}` ...