What is the process of retrieving a multidimensional array of numbers in a descending order?

Seeking help with sorting a multidimensional array in JavaScript to return it in descending order.

Here is the input:

let input = [[1,2,3],[1,3,2],[3,2,1],[3,1,2],[2,1,3],[2,3,1]]

Expected Output:

[[3,2,1],[3,1,2],[2,3,1],[2,1,3],[1,3,2],[1,2,3]]

I have attempted using the sort method:

let result = input.sort((a, b) => a - b)

However, I keep receiving the original array as output:

[[1,2,3],[1,3,2],[3,2,1],[3,1,2],[2,1,3],[2,3,1]]

I also tried using a for loop with the sort method:

for(let i = 0; i < input.length; i++){
  let inputArr = input[i]
  let output = inputArr.sort((a,b) => a - b)

  console.log(output)
}

Yet, I am getting back [1,2,3] six times (the length of the original array). How can I achieve the desired descending order?

Appreciate any guidance. Thanks!

Answer №1

For proper comparison of subarray items, it is important to compare them against each other in a logical manner. Using .sort((a, b) -> a - b) is not valid because a and b are arrays and cannot be subtracted from each other.

let input = [[1,2,3],[1,3,2],[3,2,1],[3,1,2],[2,1,3],[2,3,1]];
input.sort((a, b) => {
  // Identify the first index where the two compared subarrays differ
  const diffIndex = a.findIndex((itemA, i) => b[i] !== itemA);
   // Return the difference to prioritize the higher value in the result
   // If no difference found, return 0 to keep them next to each other
  return diffIndex === -1 ? 0 : b[diffIndex] - a[diffIndex];
});
console.log(input);
  

This method assumes that the subarrays have an equal number of elements as demonstrated in the example.

Answer №2

To properly execute the sorting process, it is essential to have numbers as input. By utilizing the .sort() method on the array input, you can achieve this by converting the inner array elements into numbers and concatenating them together - +arr.join(''). See the demonstration below for better understanding:

let input = [ [1,2,3], [1,3,2], [3,2,1], [3,1,2], [2,1,3], [2,3,1] ];

const sorted = input.sort( (a,b) => +b.join('') - +a.join('') );

console.log( sorted );
//OUTPUT: [ [3,2,1], [3,1,2], [2,3,1], [2,1,3], [1,3,2], [1,2,3] ]

NOTE

You have the option of using parseInt( arr.join('') ) instead of +arr.join('').

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

Setting up a static directory in Node Express to serve index.html along with additional tsv files

I'm encountering an issue with setting up a static folder for a project using the d3 node package. My approach involves using express to host a server.js file, which is structured as follows: var express = require("express"); var app = express(); var ...

phpUsing a foreach loop to iterate through an associative array and

I have a database table in Microsoft Access with three fields: partno, description, and quantity. However, when I try to retrieve the data and display it in an HTML table, I encounter an error message. An issue occurred while trying to access the ' ...

Setting the width of individual Views within a ScrollView to adjust accordingly in React Native

Is there a way to ensure that the Views inside my horizontal ScrollView have the same dimensions as the ScrollView itself? I'd like to implement paging so that swiping takes me to the next View within the ScrollView. I attempted using width : "100%" b ...

How can you simulate pressing Enter key using driver.execute_script?

Currently, I am working on creating an auto-login Twitter bot. I have encountered an issue where I am unable to use send_keys to fill in the password field. Interestingly, this problem only occurs with the password field as the same code works perfectly fi ...

Efficiently merging two arrays in PHP using a foreach loop

I am currently working on merging product options that are stored in a database and grouping them by the same product_id using a foreach loop. stdClass Object( [id] => 22 [product_id] => 48 [values] => Array ( [0] => stdCla ...

Determine the ranking of an array dynamically

I am exploring the most straightforward approach to implement an array with a runtime-specified rank. Specifically, in my current project, I need to store boolean values for lattice points in an array and allow users to select the spatial dimensions of th ...

Refreshing and reloading within the same jQuery function

My PHP application involves the use of 2 PHP files. chart.php - This page includes a Google chart. <div id="chart_div" style="height:100%;width:100%"> </div> <script type="text/javascript"> google.charts.load('current', ...

Struggling to get the knockout js remove function to function properly within a nested table structure

I've been encountering issues while trying to eliminate the formulation elements with the 'Delete comp' link. I can't seem to figure out why it's not functioning as expected. Moreover, the 'Add another composition' link o ...

Encountering a 422 ERROR while attempting to send a POST request

Below is the code snippet I am currently using: const url = new URL("https://api.chec.io/v1/products"); const headers = { "X-Authorization": `${process.env.NEXT_PUBLIC_CHEC_PUBLIC_KEY_SECRET}`, "Accept": "appl ...

Monitoring the validity or errors in AngularJS input fields

I'm attempting to observe the $error or $valid status of a control. Here is the control in question: <form id="myForm" name="myForm"> <input name="myInput" ng-model="myInputMdl" business-validation/> </form> The business-validat ...

How to apply bold styling to text with DOM Events

I am currently in the process of learning JavaScript and decided to practice by creating a text editor. The goal is to type something, click a button to change it to upper or lower case, bold, or italicize. While I successfully implemented the uppercase an ...

Incorporating JQuery Plugins into Angular 4 Apps

I am currently attempting to incorporate various jquery plugins, such as Magnific-Popup, into my Angular 4 application but encountering difficulties. I successfully installed jQuery using npm install --save-dev @types/jquery in the terminal, yet implementi ...

Exploring Tabletop.js to retrieve information from an array of data

Issue I am currently attempting to retrieve data from an array that contains two objects. I have implemented Tabletop.js to fetch the data from a public Google Spreadsheet, but I encountered an error in the console stating ReferenceError: object is not de ...

Is it true that Redux Saga's select function returns mutable state?

Is the state returned by Redux Saga's select function mutable or immutable? To learn more, visit https://github.com/redux-saga/redux-saga ...

Creating a JSON structure using an array in Typescript

Here is an example of my array structure: [ { "detail": "item1", "status": "active", "data": "item1_data" }, { "detail": "item2", "status": ...

Exploring the possibilities of manipulating the query string with Vue router in vue.js

I've been working on a Vue.js app that includes a tagging feature. I'm looking to implement URL parameters like where users can add tag_ids by interacting with the UI. Although I've successfully managed to update the tag_ids within the app ...

The html carousel displays stacked images instead of scrolling

I have been staring at this code for what feels like an eternity, trying to figure out why it's only displaying stacked pictures instead of a functioning carousel. Perhaps I overlooked something crucial. Could someone please lend a hand? My code is pr ...

Tips for incorporating a 'load additional' feature into a React application using Redux?

Our current method for displaying listings on the page follows this flow: To retrieve a listing of items, I utilize an action reducer (getListing()) through mapDispatchToProps class Listing extends Component { constructor(props) { super(props ...

Using Inline Styling to Showcase a Background Image in a REACTJS Component

import React from 'react'; import Slick from 'react-slick'; import style from './Slider.module.css'; import {Link} from 'react-router-dom'; const SliderTemplates = (props) => { let template = null; const ...

Populate Input Field Based on Dropdown Selection

My goal is to retrieve the value of "hargaJual" when I choose an option. However, when I add a new row to the table and select a different option, only the first row's "Harga" value changes while the second row remains empty. Take a look at the outco ...