What is the best way to organize a complicated array of arrays in JavaScript?

Within my code, there exists an array known as generationArray. Each array contained within generationArray consists of 252 elements. The first 250 elements serve as internal coding data, while the final two positions are designated for sorting criteria. The second-to-last position holds a boolean value, and the last position holds a number.

My objective is to arrange the generationArray first by the boolean values (true or false) in each array, followed by the numeric value. If the last position holds true, prioritize higher numbers first; if it's false, prioritize lower numbers first.

For example, if generationArray contains 5 arrays:

generationArray[0][last] == false
generationArray[0][last-1] == 350

generationArray[1][last] == true
generationArray[1][last-1] == 300

generationArray[2][last] == true
generationArray[2][last-1] == 250

generationArray[3][last] == false
generationArray[3][last-1] == 380

generationArray[4][last] == true
generationArray[4][last-1] == 290

The desired order would be:

generationArray[0][last] == true
generationArray[0][last-1] == 300

generationArray[1][last] == true
generationArray[1][last-1] == 290

generationArray[2][last] == true
generationArray[2][last-1] == 250

generationArray[3][last] == false
generationArray[3][last-1] == 350

generationArray[4][last] == false
generationArray[4][last-1] == 380

How can I accomplish this sorting in Javascript?

Answer №1

Here is the solution you need:

generationArray.sort(function(a, b) {
    return b[251]-a[251] || (a[251]*2-1)*(b[250]-a[250]);
})
  • b[251]-a[251] compares and casts the boolean values to integers, prioritizing true over false
  • If the previous comparison results in 0, the || condition is evaluated
  • b[250]-a[250] compares the integer values, placing larger values first
  • if the boolean value was originally false, then (a[251]*2-1)* reverses the order.

Another approach, assuming the numbers are always positive, is to consider numbers associated with true booleans as negative. By structuring your data accordingly, a simple numerical sort can be performed:

generationArray.sort(function(a, b) {
    return (a[251]?-a[250]:+a[250]) - (b[251]?-b[250]:+b[250]);
})

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

JS/Apps Script: Passing object and its keys as function parameters

When working with Google Apps Script, I have a specific task that involves looping through data and writing only certain keys to a sheet. I want this looping operation to be done in a separate function rather than directly in the main function, as it will ...

What is the best way to ensure all my borders are uniform in size?

As I work on a JavaScript project that organizes words into blocks based on their size, I encountered an issue with inconsistent border thickness in certain areas. I'm using spans to contain each word, but I can't figure out how to make the borde ...

The Vue component fails to respond to updates in plugin data

I am currently working on implementing a feature where a component reacts to data changes in a custom Vue plugin. To achieve this, the plugin creates a new instance of a Vue object in its constructor: this._vm = new Vue({ data: { obj: null, stat ...

Redis Recursion: The callstack has reached its maximum size limit

Looking for some assistance with creating a game timer. I've decided to utilize Redis and Web Sockets in order to synchronize the timer across multiple devices. However, I'm running into an issue when trying to call my function recursively using ...

Utilize two separate functions within the onchange event of a v-checkbox component in a Vue.js application

I am currently using Vue.js with Vuetify and Laravel. In one of my components, I have a dynamic datatable that fetches data from the database using axios. Within this datatable, there are v-checkboxes. Everything is functioning as expected, but now I want ...

What is the most effective method for inputting a date/time into a Django view?

Looking to create a feature where users can see what events are happening at a specific time. What is the most efficient method to implement this request? For example, if I want to display all current events, should I submit a post request to /events/2009 ...

Developing view logics in Angular using ng-grid/ui-grid

Exploring the possibilities of creating a grid with advanced features such as filtering, resizing, scrolling, fixed headers, row formatting, and cell formatting using AngularJS. After reviewing various grids documentation, I have come across the following ...

Tips for transferring a boolean value to a generic parameter in Java?

Looking to pass a boolean value to the Generic type in order to be utilized within a condition. This is the generic type interface OptionTypeBase { [key: string]: any; } type OptionsType<OptionType extends OptionTypeBase> = ReadonlyArray<Opt ...

Avoid altering the state directly; utilize setState() to update it instead. Remember to follow react/no-direct-mutation

Here's the code snippet I'm working with: constructor(props) { super(props) this.state = { loginButton: '', benchmarkList: '' } if (props.username == null) { this.state.loginButton = &l ...

How to replicate the content of a <template> tag using jQuery

Is there a way for me to clone the content of a tag using jQuery without losing the events associated with the child elements? ...

Error encountered: "Instance variable for Apex chart not defined while attempting to update charts with updateOptions."

I have integrated Apexcharts to create charts within my application. The initial data loads perfectly upon onload, but when applying a filter, I face an issue where the charts need to be refreshed or updated with the new filtered data. I attempted to use t ...

Incorporating FaceBook into a PhoneGap Application

Currently, I am working on integrating Facebook into my phonegap/cordova application. To guide me through the process, I am using the resources provided in this link: https://github.com/davejohnson/phonegap-plugin-facebook-connect/ Even though I have bee ...

In IE7, the string comparison in jQuery exhibits unique behavior

When using the following code snippet with a jQuery UI autocomplete element (#search), it works as expected in Firefox, Chrome, and other browsers, always returning true for the selected element. However, Internet Explorer 7 does not behave as expected. $ ...

The conceal feature doesn't appear to be functioning properly on jQuery Mobile

I am facing an issue with a small mobile app built using jQuery Mobile. Within a div, I have three buttons and other content. My goal is to hide these three buttons if the user's device is running on Windows (WP). The buttons are defined as follows: ...

Ways to retrieve my PHP output and display it on a page using Ajax

I'm struggling to combine the functionalities of a PHP script and Ajax on my website. I want to update content without reloading the page but facing issues. Although I can send input data through Ajax, I'm unable to retrieve the results effectiv ...

Having trouble with router.push in Vue3 and Vuex4?

Encountering some issues with Vue 3 and Vuex. Attempting to redirect users when logged in within my Vuex file, but the redirection is not happening as expected. No errors are being returned, only a link change without actually redirecting to another page. ...

Exploring the use of Dividers within Material-UI's Tabs

When attempting to include a Divider or any other element that is not a Tab within Material-UI Tabs, DOM warnings may appear in the console. <Tabs ...> //... <Divider /> //... </Tabs> One workaround for this issue involves creatin ...

Forwarding users to a new destination through a script embedded within a frame

Currently, I am facing an issue where a page (lobby_box.php) is being loaded every 4 seconds on my main page (index.php) using JavaScript. The problem arises when the code within (lobby_box.php) that is meant to redirect the client from index.php to anothe ...

What is the best way to programmatically change the event tied to an element's click

<div id="filters"></div> <div id="available"> <span class="badge badge-pill" onclick="addFilter()">Label</span> </div> function addFilter(event) { document.getElementById("filters").appendChild(eve ...

Temporary Duplicate of original data [from worldwide array]

Currently, I am developing a program that requires frequent modifications to the values in my global array. There is a specific method where I need to create a temporary copy of the global array, but this copy should only contain the initial values of the ...