Utilizing sorted array indices in reference to the original array (JavaScript)

Imagine you have a randomly arranged array of day strings like:

var days = ['Tues', 'Thur', 'Mon', 'Wed']

where days[0] = 'Tues', days[1] = 'Thurs', and so on. When you sort this array, it becomes

sortedDays = ['Mon', 'Tues', 'Wed', 'Thur']

But now, the challenge is to associate the indices of the newly-sorted array with those of the original array; for example, the old array has indices as (0, 1, 2, 3) while the new array has indices as (2, 0, 3, 1).

Figuring out how to accomplish this task can be tricky.

Answer №1

Utilize the Array.prototype.indexOf() method to locate the position (index) of an element in an array. You can execute .indexOf() on each element within your sortedDays array.

const days = ['Tues', 'Thur', 'Mon', 'Wed'];
const sortedDays = ['Mon', 'Tues', 'Wed', 'Thur'];
const sortedDaysIndices = sortedDays.map(day => days.indexOf(day));
console.log(sortedDaysIndices);

Answer №2

To obtain the sorted indexes, one can initialize an array from [0...n] and then arrange that array based on the days' sorting order.

For instance:

// Defines the sorting order for days:
const sortDays = {
    Mon:  0,
    Tues: 1, 
    Wed:  2,
    Thur: 3,
    Fri:  4,
    Sat:  5,
    Sun:  6
}

const days = ['Tues', 'Thur', 'Mon', 'Wed', 'Thur', 'Sun', 'Mon'];
// original indices
let index = Array.from(days, (_,i) => i)
index.sort((a, b) => sortDays[days[a]] - sortDays[days[b]])

// the indices are now sorted according to the days' sort order
console.log("indices: ", index.join(','))

// use the index to sort the days:
sortedDays = index.map(i => days[i])
console.log("sorted days:", sortedDays.join(','))

This method ensures that you get the correct indices even with duplicates in the initial list.

Answer №3

const weekdays = ['Tuesday', 'Thursday', 'Monday', 'Wednesday'];

const sortedWeekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday'];

const indexMapping = {}
weekdays.forEach((day, idx)=> (indexMapping[day] = { 
    oldIdx: idx  , newIdx: sortedWeekdays.indexOf(day)}
 )
)

console.log(indexMapping)

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

Tips for utilizing $http and $location in custom directives

I'm completely new to working with Angular, and I have a simple question about using $http and $location in directives. I'm trying to create a task list and would like to be able to delete an entry when clicking on a link. Right now, I've a ...

Position the Material-UI AppBar and Tab on the far right of the screen

I am trying to achieve a specific layout where the Links for "Homepage Login Settings and etc.." are placed at the right edge of the AppBar, while keeping the "Website" aligned to the left edge of the screen. Here is what I have: https://i.sstatic.net/Wvo ...

In order to preserve the data inputted by the user within a file

Check out this HTML code snippet:- ` AngularJS | $http server <div ng-controller="people"> <ul> <h2> Names and Ages of programmers: </h2> <li ng-repeat="person in persons"> { ...

What could be causing the JSON output to appear in a disordered fashion?

I am attempting to retrieve weather information for 8 different locations. Utilizing a weather API that requires longitude and latitude, it returns JSON output with the weather data for each location. I provided the coordinates in sequential order from 0 t ...

Attempting to send a POST request, only to be informed by the form that it is devoid of

I have been struggling with this problem for some time now. I implemented the category_create_post functionality in the categoryController, and everything seems to be set up correctly. I also configured the category_form.ejs to accept user input. However, ...

Unforeseen behavior in the definition of requirejs

This first snippet of code is functional: define([ 'jquery', 'underscore', 'backbone' ], function($, _, Backbone,home_template) { var HomeView = Backbone.View.extend({ render: function() { ...

I constantly encounter the dreaded "fatal error: Array index out of range" message when dealing with Swift arrays

Trying to work with arrays in Swift and encountering an issue. My goal is to create an array structured like this : var Test : [[String]] = [[]] let test_string = "HELLO" for var i = 0; i <= 15; ++i { for x in test_string.characters { ...

Is there a way to duplicate a GLTF model that has been imported into the Autodesk Viewer?

I encountered an issue while trying to dynamically clone a loaded GLB model and allow the user to position it in the scene. Despite using the model.clone() method, the cloned model ends up appearing at the same position as the original, causing changes in ...

Express get requests are failing to handle query strings

Whenever I try to extract the year and month from the URL like this: http://localhost:3000/api/posts/2018/4, the code doesn't seem to work properly. Instead, it returns an error saying: Cannot GET /api/posts/2018/4 Here's the JavaScript code I&a ...

Using AngularJs to have two ui-views on a single page

As a beginner in AngularJs, I encountered an issue with having two ui-views on the same page. When I click a button to show the view for goals, both the form for goals appear in ui-view 1 and ui-view 2 simultaneously. I have been working with states but I ...

Using Page.ResolveClientUrl in JavaScript or jQuery allows for easy resolution of client

I find myself in a predicament where I need to choose between using an HTML page instead of a .aspx page for performance reasons. Currently, I am using an aspx page solely because of the CSS and javascript file paths like: <script type="text/javascript ...

"Compilation error: 'not defined' is not recognized, 'no-undef

I am currently working on a login form that will fetch values from this API: However, the password field is currently empty, allowing any password to be accepted. This results in the error: Failed to compile 'userName' is not defined no-undef; ...

The getSession provided by the getSession function is accessible within getServerSideProps but appears as undefined within the component

Whenever I try to log the session variable inside the Dashboard component, it comes back as undefined. However, when I log it inside the getServerSideProps function, it returns the correct details. Am I missing something here? Objective: My goal is to fet ...

Mapping JSON data from Mongoose to Vue and Quasar: A comprehensive guide

I have set up a Mongoose backend and created some REST APIs to serve data to my Vue/Quasar frontend. The setup is pretty basic at the moment, utilizing Node/Express http for API calls without Axios or similar tools yet. I have successfully implemented simp ...

Creating Helper Functions for Modifying Arrays in Javascript Without Creating a New Reference: How Can I Extend the Array Class?

This library is designed for managing user lists using socket.io. I've implemented custom methods in an Array extension class. However, I've encountered an issue with the removeUser method. While logging indicates that the user is successfully ...

"Can you tell me a way to identify variances between two dates displayed in a

I am looking to calculate the differences between two dates. I will input the date values in the text box and want the duration to be displayed in another text box. <script language=javascript> function formshowhide(id) { if (id == ...

How to hide functions in Angular source code

Here's a common query. Typically, the code we develop in Angular gets compiled into a bundle file that is then sent to the browser, correct? The JavaScript code we write can be easily seen as is in the bundle file when viewing the source. How can we ...

What is the method for accessing the object in an API and updating it using jQuery?

Explanation - There are 4 selects, each choice triggers an ONCHANGE enabled function that passes the value into the Wikipedia API URL. The issue - Every time I select a different option, I want the corresponding example to appear in the title: wiki.query. ...

A lone function making two separate calls using AJAX

I have a function that includes two Ajax Get calls. Each call has a different function for handling success. function get_power_mgt_settings() { window.mv.do_ajax_call('GET',power_mgt.get_spin_down_url{},'xml',true,show ...

Using jQuery to serialize parameters for AJAX requests

I could use some help figuring out how to set up parameters for a $.ajax submission. Currently, I have multiple pairs of HTML inputs (i pairs): > <input type="hidden" value="31" name="product_id"> <input > type="hidden" value="3" name="qua ...