Arranging a string array in JavaScript according to an integer array

Looking at the provided javascript arrays:

letterArray ['a', 'e', 'i', 'o', 'u']

We also have another array that corresponds to it:

valueArray [12, 22, 7, 7, 3]

The goal is to sort the valueArray into:

[22, 12, 7, 7, 3]

However, the letterArray must be sorted in the same way as well:

['e', 'a', 'i', 'o', 'u']

How can we achieve this sorting?

Answer №1

To achieve this task, utilize the zipping method, specifically by employing the _.zip function.

// [["a", 12], ["e", 22], ...]
var arr = _.zip(letterArray, valueArray); // Combine arrays.
// Sort
// [["u", 3], ["i", 7] OR ["o", 7], ...]
var sortedArr = _.sortBy(arr, function(val) {
    // Sort based on the value array.
    return val[1];
});
// Retrieve the letter array
// ["u", "i" OR "o", ...]
var newLetterArray = _.pluck(sortedArr, "0");
// Retrieve the value array
// [3, 7, 7, ...]
var newValueArray = _.pluck(sortedArr, "1");

It is worth noting that the presence of duplicate numbers in your example complicates matters and may lead to unpredictability in sorting order. The order of "i" or "o" will vary depending on the browser used.

Answer №2

One way to organize your data is by zipping up two arrays into a combined array, like

[[12,'a'], [22, 'e'], [7, 'i'], [7, 'o'], [3, 'u']]
, and then sorting the combined array to easily read off the letters. Another approach is to create your own sorting algorithm and synchronize changes between the integer and letter arrays.

In my opinion, method 1 utilizing a built-in sorting algorithm is more efficient and less labor-intensive than creating a custom sorting algorithm for synchronization purposes.

Answer №3

// The function myArray.zip takes N arrays and combines them into one array with all pieces interleaved
// Example: [1,2,3].zip([4,5,6],[7,8,9]) -> [ [1,4,7], [2,5,8], [3,6,9] ]
(function(o){
  var zip = function(){
    var argLen = arguments.length;
    var result = new Array(this.length);
    for (var i=this.length-1;i>=0;--i){
    var a = result[i] = [this[i]];
    for (var j=0;j<argLen;++j) a[j+1] = arguments[j][i];
    }
    return result;
  }
  if (Object.defineProperty) Object.defineProperty(o,"zip",{value:zip});
  else o.zip = zip;
})(Array.prototype);

var letters = ['a', 'e', 'i', 'o', 'u'];
var values  = [12, 22, 7, 7, 3];
var valuesAndLetters = values.zip(letters);
// [[12,"a"],[22,"e"],[7,"i"],[7,"o"],[3,"u"]]

var sorted = valuesAndLetters.sort(function(a,b){
  // Sort in descending order, first by value, then by letter
  return a[0]<b[0]?1:a[0]>b[0]?-1:a[1]<b[1]?1:a[1]>b[1]?-1:0;
});
// [[22,"e"],[12,"a"],[7,"o"],[7,"i"],[3,"u"]]

Edit: If you don't have (or want to rely on) defineProperty, and don't want to extend Array.prototype as a fallback, then here's a version of zip that doesn't touch anyone's prototype:

// Combines N arrays into one array with all pieces interleaved
// e.g. Array.zip([1,2,3],[4,5,6],[7,8,9]) -> [ [1,4,7], [2,5,8], [3,6,9] ]
Array.zip = function zip(a0,a1,etc,aN){
  var argLen = arguments.length;
  var result = new Array(a0.length);
  for (var i=a0..length-1;i>=0;--i){
    var a = result[i] = [a0[i]];
    for (var j=1;j<argLen;++j) a[j] = arguments[j][i];
  }
  return result;
};

var letters = ['a', 'e', 'i', 'o', 'u'];
var values  = [12, 22, 7, 7, 3];
var valuesAndLetters = Array.zip(values,letters);
// [[12,"a"],[22,"e"],[7,"i"],[7,"o"],[3,"u"]]

var sorted = valuesAndLetters.sort(function(a,b){
  // Sort in descending order, first by value, then by letter
  return a[0]<b[0]?1:a[0]>b[0]?-1:a[1]<b[1]?1:a[1]>b[1]?-1:0;
});
// [[22,"e"],[12,"a"],[7,"o"],[7,"i"],[3,"u"]]

Answer №4

function unique_sort_method(arrayOfIntegers, arrayOfCharacters){
    var min = arrayOfIntegers[0]
    for(index in arrayOfIntegers){
        //implement a custom sorting algorithm
        // that allows you to preserve the original indexes and then map them to the respective character array indexes
    }
}

Answer №5

Using the method of zipping may seem straightforward, but for a more thorough solution, you can consider utilizing an index array:

var letterArray = ['a', 'e', 'i', 'o', 'u'];
var valueArray = [12, 22, 7, 7, 3];
var indexArray = [0, 1, 2, 3, 4]; // It's recommended to calculate these values dynamically
indexArray.sort(function(a, b) { return valueArray[a] - valueArray[b]; });

In order to obtain an array of letters sorted by their corresponding values, iterate through the indexArray and retrieve the letter at each index.

Answer №6

If I were to approach this task differently, I would opt for utilizing a single array containing objects instead of two arrays. By doing so, you have the flexibility to create your own custom sorting function, providing you with maximum control over the data structure.

lettersAndValues = [{letter: 'a', value: 12},
                      {letter: 'e', value: 22},
                      {letter: 'i', value: 7},
                      {letter: 'o', value: 7},
                      {letter: 'u', value: 3}];

function valueComparison(obj1, obj2) {
    if (obj1.value < obj2.value) {
        return 1;
    }
    else if (obj1.value > obj2.value) {
        return -1;
    }
    else { 
        return 0;
    }
}

lettersAndValues.sort(valueComparison);

// => [Object { letter="e", value=22}, 
//     Object { letter="a", value=12},
//     Object { letter="i", value=7}, 
//     Object { letter="o", value=7}, 
//     Object { letter="u", value=3}]

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

Passing an array list back to the parent component in ag-grid(Vue) - A step-by-step guide

Currently, I am integrating AG Grid with Vue. My project has a specific requirement where two checkboxes are displayed using a cellRendererFramework. However, I am facing difficulties in fetching the values of these checkboxes from the row definitions. The ...

Setting up a service URL with parameters using a versatile approach

I am faced with a situation where I have over 200 service URLs that follow a specific format: serviceURL = DomainName + MethodName + Path; The DomainName and MethodNames can be configured, while the path may consist of elements such as Param1, Param2, an ...

Dynamically adjust row height in AG Grid within an Angular application based on the visibility of other columns

My current AG-Grid version is 21.2.1, and I am unable to upgrade it for certain reasons. I have successfully implemented wrapping cell content to ensure all content is visible. Additionally, I have buttons in my application to toggle the visibility of col ...

Unable to display menu content text using jQuery

Currently experimenting with jQuery to create a dynamic submenu. The goal is to have a sub menu appear when the main menu is clicked, and then disappear when an item in the sub menu is selected, revealing additional information within a div. Unfortunately, ...

Extracting values from URL query parameters in Vue.js

When dealing with Vue.js callback URLs, I encounter situations where I need to extract a parameter value from the URL. For instance, consider this return URL: http://localhost:8080/#/sucesspage?encryteddata=abdeshfkkilkalidfel&9a I attempted to retrie ...

Tips for triggering window load event on a particular page

I need to trigger the windows.load event on a specific page. Currently, I have set it up like this: $(window).load(function(){ if(document.URL == "/car-driving.html") { overlay.show(); overlay.appendTo(document.body); $('.popup' ...

Modify the useRef value prior to the HTML rendering (React functional component)

Hello everyone, I am attempting to update the value of useRef before the HTML is rendered. I have tried using useEffect for this purpose, but it runs after the HTML is ready, making it unsuitable for my needs. What I want to achieve is resetting the value ...

Having trouble aligning my slider in the center

Despite trying various methods to center this slider, such as using align="center" and different margin styles on the images and slider div itself, I am still facing alignment issues. Any assistance would be greatly appreciated. This is my first time posti ...

Steps to eliminate a choice from the MUI Datagrid Column Show/Hide feature

I am attempting to customize which columns are displayed on the <GridToolbarColumnsButton/> component within the MUI Datagrid toolbar (refer to the image below) https://i.stack.imgur.com/joZUg.jpg Potential solution: I have been exploring the AP ...

Struggling to Parse JSON Responses?

Utilizing AJAX/JQuery to communicate with a WCF service presents its own set of challenges. One common method is implementing .NET try/catch error-handling on the service-side to manage different scenarios, such as user timeout errors. Typically, the servi ...

Utilizing Rails' JSON response with Ember.js

This is a sample serializer class TestSerializer < ActiveModel::Serializer attributes :post def post @post = user.joins(:post).select("user.name as name,post.content as content").where("user_id = ?",object.id) end end I'm try ...

Guidelines on Transferring Variables to a JavascriptExecutor Script

Currently, I am utilizing C# and Selenium to browse through a website and have come across an issue regarding passing variables into my JavaScriptExecutor command. When I attempt to do so using the code below: ((IJavaScriptExecutor)webdriver).ExecuteScript ...

Having difficulty accessing the 'makeCurrent' property of an undefined object in Angular mobile application

I have followed the steps outlined in the Angular mobile toolkit guide found at https://github.com/angular/mobile-toolkit/blob/master/guides/cli-setup.md My Node version is v4.4.3 NPM version is 2.15.1 The issue arises when I run the command $ ng serve, ...

What steps can I take to allow a third-party JavaScript to access my TypeScript object?

I am working on an Angular application and I have a requirement to develop an API for a third-party JavaScript that will be injected dynamically. public class MyApi{ public callSomeFunction():void{...} public getSomeValue():any {...} } var publicA ...

What is the best way to remove jest from your system completely?

I've been trying to set up jest for testing react applications However, after installing it with yarn, I am encountering issues starting my react app in any way This error message keeps popping up, but the suggested solution didn't resolve it: ...

Combining user input data using JavaScript and Vue.js

I am working on a form using Vue.js and I want to combine the data from the input fields upon submission. I have been struggling to achieve this and created a jsfiddle to showcase my attempt. In my form, I have three Vue components for each of the input f ...

Error occurred in child process while processing the request in TypeScript: Debug Failure encountered

I encountered the following error in TypeScript while running nwb serve-react-demo: Child process failed to handle the request: Error: Debug Failure. Expression is not true. at resolveNamesWithLocalCache (D:\Projects\react-techpulse-components& ...

Retrieving data from MongoDB for rendering on an HTML page

I have successfully inserted data into my MongoDB database, but I am facing issues with the "get" function to display this data on my HTML page. My current setup involves using Node.js with Express framework and Angular for front-end development and routi ...

Issues with the event firing in the Polymer component for google-signin?

I recently set up a new starter-kit project using polymer-cli 1.7 and I'm attempting to incorporate Google authentication utilizing the google-signin element. Although the sign in button appears and works for signing in, the signedIn property isn&apo ...

Issues with AngularJS <a> tag hyperlinks not functioning as expected

After performing a search, I have an array of objects that needs to be displayed on the template using ng-repeat. The issue arises when constructing the URL for each item in the array – although the ng-href and href attributes are correct, clicking on th ...