Arranging an array based on the elements of another array in JavaScript

Imagine you have an array of Person objects:

var people = [{name: "Joe Schmo", age: 36}, {name: "JANE DOE", age: 40}];

and there's a function that can sort an array of strings in a case-insensitive manner:

function caseInsensitiveSort(arr) { ... }

Is there a simple way to integrate the existing sort function with Array.prototype.map to sort the people array based on the name key only?

This would result in:

var people = [{name: "JANE DOE", age: 40}, {name: "Joe Schmo", age: 36}];

While it can be manually achieved like this:

people.sort(function (a, b) {
    return a.name.localeCompare(b.name);
});

I'm unable to think of a way to utilize the pre-existing sort function efficiently. This could be particularly useful when dealing with more customized sorting functions.

It seems challenging to determine the original indices after sorting the proxy array using the native JS sort function. This limitation makes it difficult to achieve the desired outcome effectively.

In my attempts at solving this, I realized the approach was inefficient. Thankfully, a solution utilizing a comparison function is presented below.

Answer №1

If you want to order the people array based on the sorted names array generated by your existing function, you can follow this approach:

var sortedNames = customSortFunction(people.map(function(person) { 
    return person.name;
}));

people.sort(function (a, b) {
    return sortedNames.indexOf(a.name) - sortedNames.indexOf(b.name);
});

However, for better efficiency, it is recommended to separate the comparison logic from your sorting function and create a dedicated customCompareFunction.

With this enhancement, the code would look like this:

people.sort(function (a, b) {
    return customCompareFunction(a.name, b.name);
});

Answer №2

To implement your caseInsensitiveSort() function effectively, consider utilizing the .toString() method in the following way:

var sortedPeople = people.map(function (person) {
    return {
        person: person,
        toString: function () {
            return person.name;
        }
    };
});

caseInsensitiveSort(sortedPeople);

people = sortedPeople.map(function (item) { return item.person; });

If using .toString() is not feasible, another approach is to sort the names, map them to their respective indices, and then rearrange the people based on this mapping:

var names = people.map(function (person) { return person.name; });

caseInsensitiveSort(names);

var nameIndexMap = {};
names.forEach(function (name, i) { 
    nameIndexMap[name] = i;
});

people.sort(function (a, b) {
    return nameIndexMap[a.name] - nameIndexMap[b.name];
});

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

Manipulate a JavaScript array for optimal utilization in Google Charts by flattening the days nested within the array

Here is an array [ ["04/21/2021", 405, 85, 30] ["04/18/2021", 350, 135, 30] ["04/16/2021", 335, 120, 30] ["04/15/2021", 420, 100, 30] ["04/15/2021", 405, 85, 30] ["04/15/2021", 350, 13 ...

I am looking to adjust/modulate my x-axis labels in c3 js

(I'm specifically using c3.js, but I also added d3.js tags) I have been working on creating a graph that displays data for each month based on user clicks. However, I am facing an issue where the x-axis labels show 0-X instead of 1-X. For instance, ...

Troubleshooting Problems with array.filter() Method in JavaScript

Currently, I am working on a JavaScript function that seems to be functioning properly in all browsers except for IE and Safari. Strangely enough, my editor is flagging an error on line 4. The function's basic concept involves taking the ID of an HTML ...

Spinning html/css content using JavaScript

Greetings! I am currently working on a demo site using just HTML, CSS, and JavaScript. Typically, I would use Ruby and render partials to handle this issue, but I wanted to challenge myself with JavaScript practice. So far, I have created a code block that ...

Strange sequence of results coming from Vue.js

methods: { ShowWindow: function(QueryID) { this.$data.ID = QueryID; if(this.GetData()) { console.log("asdasd") } document.querySelector("#EditWindow").style.visibility = "visi ...

Dynamic image updates in real-time

Beginning a new project and already facing a roadblock, I could really use some assistance. I have 16 (4x4) images that I am displaying on a page. $max_images = $_GET['images']; $num_images = $max_images; while (($num_images > 0) && ...

When the button is clicked, I would like to use JavaScript to toggle the visibility of a div, allowing it to open and

I am attempting to toggle a div using JavaScript when the open and close button is clicked. However, I have encountered an issue where the div disappears when the button is clicked, possibly due to post-back. var toggle = function () { var mydiv = d ...

Is there a way to append a unique property with varying values to an array of objects in TypeScript?

For instance: items: object[] = [ {name: 'Backpack', weight: 2.5}, {name: 'Flashlight', weight: 0.8}, {name: 'Map', weight: 0.3} ]; I prefer the items to have an 'age' property as well: it ...

Updating a Mongoose model with a dynamically generated field name

I am attempting to pass a field name as a variable, but here is the code I tried and it isn't working: var update = {}; update[req.body.field] = req.body.value; Model.update( {"email": req.user.email}, {$set: {update}}, function (err, suc ...

The outcome of AES encryption varies when comparing Node JS with C# programming languages

In a particular scenario, I need to encrypt and transmit text using the AES 256 algorithm. The decryption process will be handled by client-side C# code. Here is the encryption code in JavaScript: const crypto = require('crypto'); algorithm = ...

What is the best way to transition an absolute positioned element from right to center?

When hovering over an overlay element, I want the <h3> tag to appear with a transition effect from right to center, similar to the example shown here. Could someone please assist me in achieving this? Thank you in advance. HTML <div class="row m ...

The currently ineffective process of sorting the array based on user input needs to be fixed in order

# starting point def start(): # create list and initialize variables golfScores = [] index = 0 SCORES = 10 # input scores 10 times while (index <= SCORES - 1): scoreInput = int(input('Enter score: ')) g ...

Issue with jQuery datepicker not triggering onChangeMonthYear event

Recently, I've been working on creating an app using jQuery date picker. To see my progress so far, feel free to check out this fiddle: http://jsfiddle.net/Lf6sD/2/. In the options, there's a mention of an onChangeMonthYear event that should trig ...

What is the reason behind Rxjs switchMap only emitting the final value from an of() observable source?

Here are two code snippets, one using map and the other using switchMap. The functionality of map is clear: of('foo', 'bar') .pipe(map((val) => sanitizer(val))) .subscribe((val) => console.log('value:', val)); func ...

My goal is to eliminate unnecessary code and transfer it into its own jQuery function

Currently, I am working on optimizing my code by removing redundancies and moving sections to separate functions. //Consolidating Infotypes for filtering and checking if any option is selected if(this.$infoOptions.val() != null){ ...

Ways to pass an instance variable between different files in Node.JS?

Currently, I am in the process of constructing a Telegram bot and utilizing the npm package found at: https://www.npmjs.com/package/node-telegram-bot-api My project structure looks like this: https://i.sstatic.net/tllMw.png Within my app.js file, I init ...

JavaScript function for searching YouTube videos

While browsing on stackoverflow, I came across the following code snippet: $(document).ready(function () { $("#show").click(function () { getYoutube($("#Search").val()); }); }); function getYoutube(title) { $.ajax({ type: "GET", url: yt_url ...

How can I protect my security_access_key in a React.js application?

For security reasons, I am hesitant to import the security_access_key directly into my application. I attempted to access it through an environment variable like so: Step 1: Added the security_access_key to the .env file security_access_key=abc123 St ...

The CORS policy has blocked the request due to the header being set

Recently, I've been working on building a server using NodeJS with express and have come across an obstacle regarding the CORS policy. In my server's code snippet, this is what I have: app.get(`/important`, function(req,res){ fs.readFile(&apo ...

Organizing items by a string attribute in TypeScript

My data consists of an array of objects with a structure similar to this: export class AccountInfo { accountUid: string; userType: string; firstName: string; middleName: string; lastName: string; } NOTE: I opted not to use an enum for userType ...