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

When I remove a user as admin, I am unable to retrieve all users to update the data table

I am currently working on an Admin Dashboard that includes a section for users. This section features a simple table displaying all the users in the MongoDB database along with some information. Additionally, there are functionalities to add a new user and ...

Is it possible to trigger Material UI Dialogs from the Parent Component?

Looking for help on how to open two separate Material UI dialogs (Terms & Privacy) from their parent component, a Material UI 'simple menu'. I have already imported and nested them in the parent component, but struggling to figure out how to trig ...

Guide to comparing the contents of two text fields and highlighting the altered characters using ReactJS

Is there a way to compare the contents of two Material-UI textfields and identify the characters that have changed in both? I came across a similar question, but it was specifically for ReactJS rather than C# Windows Forms: How can you highlight the chara ...

Generate a collection of elements using a different collection as a reference

I am struggling with an array of objects: let data = [{ createdDate: "2222", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="087c6d7b7c3d487c6d7b7c266b6765">[email protected]</a>", histories: [ ...

Review the Drawer Item's Render Method

I have been using react-native with expo and following a specific guide closely: Is there an alternative way to implement this without the use of icons at the moment? Upon compiling, I encountered an error regarding the Render Method of DrawerItem. I&apo ...

Issue: TableHead inside an Expandable Row in MUI-Datatable is being duplicated for each row, causing the table to not be centered.Explanation: The

Can anyone help me with this issue? I'm having trouble with my table where the headings are repeating for every row and the table is stuck on the far right side. How can I center the table instead? Codesandbox: https://codesandbox.io/s/xenodochial-fo ...

Connecting Peers in Windows Store App using HTML/JS

I am curious to find out if anyone has successfully created a peer-to-peer app for the Windows Store using HTML5 and JavaScript. I want client A of the app to be able to establish a connection with and send data to client B through either a TCP or UDP sock ...

Incorporate a hyperlink into a React Material-UI DataGrid

While utilizing the DataGrid component from Material-UI, I am trying to add a link to the end of each row. However, the output is currently displaying as: ( [object Object] ). https://i.stack.imgur.com/2k3q2.png I would like for it to show the record ID, ...

What is the proper way to utilize the ES6 import feature when using a symbolic path to reference the source file?

I am seeking a deeper understanding of the ES6 import function and could use some assistance. The Situation Imagine that I have a portion of code in my application that is frequently used, so I organize all of it into a folder for convenience. Now, in t ...

Utilize a singular object to contain multiple instances of the useState hook

const [regionData, setRegionData] = useState({ country: "", city: "", population: "", location: "", temp_min: "" }); Does anyone know a more efficient and cleaner way to replace these individual useState hooks by organizing them into ...

Converting a string array to an array object in JavaScript: A step-by-step guide

My task involves extracting an array from a string and manipulating its objects. var arrayString = "[{'name': 'Ruwaida Abdo'}, {'name': 'Najlaa Saadi'}]"; This scenario arises when working with a JSON file where ce ...

Tips for exchanging JavaScript variables with PHP using AJAX

Hey there, I'm new to JavaScript and I've hit a roadblock with passing variables to PHP using Ajax. <script> $date = "123"; $.ajax({ url: './record.php', type: "POST", ...

Exploring the option of showcasing multiple json_encode data on a pie chart

Hey there! I'm currently utilizing Chart.js to generate a pie chart by retrieving data from the database: <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script> <script> var ctx = document.getE ...

Dealing with network issues when submitting a form

Is there a smooth way to handle network errors that may arise during the submission of an HTML form? It is important for me not to have the browser cache any information related to the form, but I also want to ensure that the user's data is not lost i ...

Next.js is throwing a TypeError because it does not recognize the function fs.readFileSync

In my JSON data file called total.json, I store information for a chatbot. { "guilds": 3, "users": 21 } Within my index.tsx file, I want to display this data on the webpage, so I attempt the following: import fs from 'fs'; f ...

What is the best way to swap out elements in my string with those from an array?

Struggling to replace special characters in file names before saving them to the Windows filesystem due to compatibility issues. For my initial approach, I used the replace() method repeatedly on the string to replace specific special characters. Here&apo ...

looping through the elements in a collection using a for-in loop

Issue with IE 11 Console Chrome Console Behavior When changing the word 'item' to 'anotherItem' in the loop like so: var obj = { id1: 'item 1', id2: 'item 2', id3: 'item 3' }; for (anothe ...

How can I make tooltipster display tooltips properly?

I have been struggling to customize tooltips using a library called tooltipster. Here is what I currently have: Head of index.html: <head> <!--TOOLTIP CSS--> <link rel="stylesheet" type="type/css" href="node_modules/tooltipster-master ...

Toggle jQuery to hide a div and update its CSS styling

There is an anchor with the class of "hide-btn1" that I want to trigger a series of actions when clicked: The rcol-content should hide and the text should change from Hide to Show The #container width needs to increase to 2038px The table.status-table wi ...

NodeJS is capable of handling a limited number of requests at a time

Utilizing jQuery to send requests to a local server has been causing some issues. After sending approximately 4-7 requests, the port stops working without any visible error. Eventually, after a few minutes, some of the requests are successfully sent to the ...