Tips for organizing a multi-dimensional array based on various column indexes

I am looking to organize a multidimensional array by multiple column index.

Take, for instance, the test data provided below:

var source = [
  ["Jack","A","B1", 4],
  ["AVicky","M", "B2", 2],
  ["AVicky","F", "B3", 3],
];

I need to be able to dynamically sort the 'source' array based on different combinations of column indexes. For example, sorting first by first and second columns, and then next time by all three columns.

The current code I have tried only allows me to sort based on a specific column index as shown below:

var source = [
  ["Jack","A","B1", 4],
  ["AVicky","M", "B2", 2],
  ["AVicky","F", "B3", 3],
];
var target = [  
  ["Tom","M", "B3", 2],
  ["Jack","F", "B1", 1],
  ["Cindy","F", "B3", 3],
];
var keyIndexs = [0,1];
var same = [];
//order rows
var sourceOrder =  source
keyIndexs.forEach(i => sourceOrder = sortByColumn(sourceOrder, i)) ;
console.log(sourceOrder);
for(var i = 0; i < source.length; i ++){
  //console.log(ContainsRow(source[i], target));
  if(ContainsRow(source[i], target)){
    same.push(source[i]);
  }
}
console.log(same);

function CompareRow(source:any[], target:any[]):boolean{
  return JSON.stringify(source) === JSON.stringify(target);
}

function ContainsRow(source:any[], target: any[][]):boolean{
  for(var i = 0; i <target.length; i ++){
    if(CompareRow(source, target[i])){
      return true;
    }
  } 
  return false;
}

function sortByColumn(a, colIndex){
  a.sort(sortFunction);
  function sortFunction(a, b) {
      if (a[colIndex] === b[colIndex]) {
          return 0;
      }
      else {
          return (a[colIndex] < b[colIndex]) ? -1 : 1;
      }
  }
  return a;
}

Answer №1

Here is a way to achieve the desired result:

const sortCompareFunc = sortingArray => (firstVal, secondVal) => {
  const getValue = val => sortingArray.reduce((acc, curr) => acc + val[curr], '')
  const firstValue = getValue(firstVal)
  const secondValue = getValue(secondVal)

  return typeof firstValue === 'string'
    ? firstValue.localeCompare(secondValue)
    : firstValue - secondValue
}

const data = [
  ["Jack", "A", "B1", 4],
  ["AVicky", "M", "B2", 2],
  ["AVicky", "F", "B3", 3],
]

const sortingCriteria1 = [1]
const result1 = data.sort(sortCompareFunc(sortingCriteria1))
console.log('result1:', result1)

const sortingCriteria23 = [2, 3]
const result23 = data.sort(sortCompareFunc(sortingCriteria23))
console.log('result23:', result23)

const sortingCriteria3 = [3]
const result3 = data.sort(sortCompareFunc(sortingCriteria3))
console.log('result3:', result3)
.as-console-wrapper { max-height: 100% !important; top: 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

Typescript: Delay code execution until a function has completed running

I've encountered an issue with my code that involves calling a function. Here is the snippet of code in question: this.getAllOptions(questionID); console.log("++++++++++++++++++++++++++++++++"); console.log(this.result); The task of this function is ...

Determine the sum of exported identifiers based on ESLint rules

Currently, I am facing a requirement in my JavaScript/TypeScript monorepo to ensure that each library maintains a minimal amount of exported identifiers. Is there any existing eslint rule or package available that can keep track of the total number of exp ...

The HiddenField is returning empty when accessed in the code behind section

In my gridview, the information is entered through textboxes and saved to the grid upon clicking a save button. One of these textboxes triggers a menu, from which the user selects a creditor whose ID is then saved in a HiddenField. <td class="tblAddDet ...

Is it possible for a user to change the data stored in sessionStorage variables?

Incorporating client-side JavaScript into my project to save certain variables using Web Storage - specifically, the sessionStorage. However, uncertainty exists regarding whether a user holds the capability to alter these variable values. If this is indee ...

Retrieving Substring before Specific Character in PHP

Imagine I have a String like this: $b = 'grapes, pineapple & fruit seller offered by flipkart from usa'; From this sentence, what I need are 3 specific words: grapes pineapple fruit seller The first word can be extracted using the explod ...

Generating Speech from Text using jQuery API in HTML

Can a website be created to detect textbox text upon longClick by the user, and function across various browsers? The site should also have mobile compatibility. Appreciate any help! ...

Validating complex ASP.NET MVC objects using AngularJS

I am encountering an issue with validating my model in a subform using AngularJS. Despite making changes to the SearchPostCode values and seeing updates in classes, the error message fails to display, and the button remains disabled. <form novalidate&g ...

css based on the current time in the United States

I have a working code that currently reads the user's computer time, but I specifically need to get the hours from the USA regardless of the user's location. The CSS should be applied based on USA time. <script type="text/javascript"> dat ...

What is the reason for the failure of the "keyof" method on this specific generic type within a Proxy object created by a class constructor?

I'm encountering difficulties when utilizing a generic type in combination with keyof inside a Proxy(): The following example code is not functioning and indicates a lack of assignable types: interface SomeDataStructure { name?: string; } class ...

Leveraging jQuery to automatically fill in a time field while excluding other buttons

I've been working on using jQuery to automatically fill in a time input field. The functionality is working properly, but the time is also being applied to my other button. How can I make sure it only gets assigned to the time input field? I would re ...

What causes a browser to redirect when trying to update the value of the alt field in a Wordpress media image?

Attempting to create a bookmarklet for the Wordpress image gallery manager that triggers the sidebar when an image is clicked. The sidebar contains fields for alt text (input), legend, and description (both textarea). <a href="javascript:var t=document ...

Running a <script> tag with an external src attribute in a dynamic manner through the use of eval

Currently, I am utilizing the Genius API to fetch lyrics for a particular song and then embed them within an HTML <div> tag. My interaction with this API is through PHP, employing an AJAX GET request. Upon a successful AJAX request, the following HT ...

What is the process for adding to a highly nested array in mongoose?

Here is the Model I am working with: const MessagesSchema = mongoose.Schema({ //for individual message text: { type: String, required: true } }, { timestamps : true }) const MessagesCollectionSch ...

The Typescript Decorator is triggered two times

I submitted a bug report regarding Typescript because I suspect there is an issue, although I'm seeking additional insights here as well. This is the scenario. When running the following code: class Person { @IsValueIn(['PETER', ' ...

Creating a file logging system with console.log() in hapi.js

I have recently developed an Application with Hapi.js and have utilized good-file to record logs into a file. However, I am facing an issue where the logs are only written to the file when using request.log() and server.log() methods. My goal is to also lo ...

Element not chosen in Angular version 6

Recently delving into Angular 6, I've been working on setting up form validation within an Angular form. Validation has been successfully implemented, but there's a minor issue with the select box displaying an empty first value. Here is my code ...

It appears that the functions in linqts are not clearly defined

Currently, I am in the process of learning Angular4 and facing challenges with getting linqts to function properly. Within my room-list.component.ts file, I include it in this manner: import { List } from 'linqts'; A few lines below, I have my ...

Modifying the structure of serialized data

After serializing a JS form, the data looks like this: .....&xx=xxx&otherError=&input=SMS&message=sdfgs&...... Can anyone provide guidance on how to replace the value of message with the content of a textarea before making an ajax cal ...

How can XML data be effectively showcased on a website?

I have a service that generates XML files every 10 seconds with server information. I am seeking a solution to showcase this data on a webpage. After researching online, it appears that utilizing AJAX would be beneficial as it permits the loading of dynam ...

Having difficulty converting an object into an iterable using an arrow function

Currently immersed in learning JavaScript, I successfully created a class and now find myself faced with the task of making it iterable. The Group class represents a collection of values, akin to a Set, equipped with methods for adding, removing, and che ...