Sort an array using a custom sorting algorithm in Javascript

In my current function, I am able to sort an array alphabetically.

function compare(a,b) {
    if (a.subtitle < b.subtitle)
        return -1;
    if (a.subtitle > b.subtitle)
        return 1;
        return 0;
}

Now, I am in need of a similar function that will allow me to sort the array based on another array. Despite my attempts to write this function myself, I was unable to figure it out and ended up with nothing.

For example:

I want Array1 to be sorted according to its position in Array2.

Array1 = ['quick','fox','the','brown'];
Array2 = ['the','quick','brown','fox'];

It seems like there should be a simple solution to this problem that I'm just not seeing.

Edit:

In addition, any items present in Array1 that are not in Array2 can simply be added to the end without any specific order or alphabetization for simplicity's sake.

Answer №1

Check out this solution:

function sorting(a,b, sortArray) {
    if ((sortArray.indexOf(a) != -1 && sortArray.indexOf(a) < sortArray.indexOf(b))
         ||  sortArray.indexOf(b) == -1)
        return -1;
    if ((sortArray.indexOf(a) > sortArray.indexOf(b))
         || sortArray.indexOf(a) == -1)
        return 1;
        return 0;
}

Answer №2

http://jsfiddle.net/BFAQJ/

const wordsArray = ['quick', 'fox', 'the', 'brown', 'abc']; //original array to be sorted
const referenceArray = ['the', 'quick', 'brown', 'fox'];
let sortedWords = [];

for (let i = 0; i < referenceArray.length; i++) {
    let index = wordsArray.indexOf(referenceArray[i]);
    if (index !== -1) {
        console.log(index);
        sortedWords.push(referenceArray[i]);
        wordsArray.splice(index, 1);
    }
}

for (let j = 0; j < wordsArray.length; j++) {
    sortedWords.push(wordsArray[j]);
}

console.log(sortedWords);

Answer №3

Today, I came across a situation where I needed to achieve the same result. Here is the approach I took:

var arr = [".", 5359, 1, 2, 3, 4, 6, 9, 15];
var priorities = [3, '.', 1, 4, 15, 9, 2, 6];

var resultArr = arr.filter( function(arrElement) { return priorities.indexOf(arrElement) >= 0 })
    .sort( function (a,b) { return priorities.indexOf(a) - priorities.indexOf(b) })
    .concat( arr.filter( function(arrElement) { return priorities.indexOf(arrElement) < 0})
);

console.log(resultArr.join(""));

Output: 3.14159265359

View jsfiddle inspired by @rps's solution

In essence, this code selects elements based on a specified order, sorts them accordingly, and then appends elements without specific ordering preferences. An added benefit is that the sorting does not alter the original order of arr.

Whether this method is superior or inferior, I personally dislike using for loops. :)

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

How to efficiently switch between classes in Ember Octane using Handlebars?

What is the best way to toggle between displaying a class on and off using Ember.js Octane? Should I use an @action or @tracked in this case? <img src="flower.jpg" alt="flower" class="display-on"> or <img src="flower.jpg" alt="flower" class=" ...

Combine an array nested within an object with each key of the object

Alright, let's dive into the structure of these objects: custom_fields:{ 21:{ edit:true required:true show:true } } In my Angular controller, this object is stored under $scope.page.custom_fields. Within this object, there is another ...

Having trouble with Visual Studio recognizing the src attribute while attempting to reference the index.js file

Currently, I am working on my javascript code within the "index.js" file. However, I have encountered an issue when using the src attribute in the "index.html" file. It seems that the code is not functioning properly. Just to provide some context, I am uti ...

selenium-webdriver causing issues on a nodejs server

Encountering an error while trying to start the nodejs server with selenium webdriver ubuntu@ip-10-10-10-193:~/testenvoy$ node app.js /home/ubuntu/testenvoy/node_modules/selenium-webdriver/index.js:115 static createSession(...args) {} ...

Pause the for loop until all nested asynchronous database calls are completed

Currently, I am utilizing the listCollection method within mongodb to loop through each collection that is returned using a query with find. The issue arises when I attempt to construct an object within the loop that I intend to return with response.json ...

Is the Okta SDK compatible with all identity providers?

I am looking to incorporate a wide range of Identity providers into my app, such as Auth0 SSO OIDC, Onelogin SSO OIDC, Google SSO OIDC, and others. Is it possible to use this solution to make that happen? https://github.com/okta/okta-auth-js ...

Display the properties of the nested object

I am trying to extract and print the postal_code value from the JSON file provided below: { "results" : [ { "address_components" : [ { "long_name" : "286", "short_name" : "286", "t ...

Reactjs Rendering problem with retrieving data from the backend in a popover

Take a look at the test environment where this problem is occurring https://codesandbox.io/s/nice-cache-kl12v My website design is being done with antd. Right now, I'm facing an issue where I need to display notifications to the user, which are acces ...

Is it possible for the JavaScript code to cease execution once the tab is closed?

I am working on a JavaScript code snippet that is designed to execute once a component finishes loading: function HelloThere() { React.useEffect(() => { setTimeout(() => { // code to make a server call to write data to DB ...

Converting a string to a JSON array with Jackson in RESTful APIs

As I delve into the world of JSON and REST, I find myself testing a REST API that returns strings in the following format: [{ "Supervisor_UniqueName": "adavis", "Active": "true", "DefaultCurrency_UniqueName": "USD", "arches_type": "x-zensa ...

Leveraging useEffect (or a comparable method) within a class component to create a loading screen

As a React newbie, I recently created a loading screen using useEffect in a functional component. Now, I'm trying to achieve the same using class components, but I'm facing some challenges. Here is the functional component that works perfectly: c ...

Issue with jQuery arises in chrome extensions while utilizing the popup feature

Imagine a scenario where you have a website with a disabled button. Now, you want to create a popup extension that, upon clicking a button in the popup, will remove the disabled tag from the button on the website. //manifest.json { "name": &quo ...

Angular ng-boostrap modal automatically refreshes upon detecting mouse movement with an embedded video

Currently, I am facing an issue with my Angular 7 ng-bootstrap modal. The problem arises when the modal, which includes a video player within an <iframe>, is moved to the production system. Whenever there is any mouse movement detected, the video get ...

Issue with MUI DataGridPro failing to sort the email field

I am facing an issue with the sorting functionality in the email field while creating a table using MUI DataGridPro. The sorting works fine for all other fields except for the email field. Adding some random text here to ensure my question is published. Pl ...

Encountering the React.Children.only error while trying to use the <Link> component in Next.js

I'm encountering an issue with the code below: Error: React.Children.only expected to receive a single React element child. While trying to troubleshoot, I noticed that it only allows me to have one header under the link. <div className="co ...

JavaScript and jQuery: The Power of Dynamic Arrays

Even though my var email contains a string data, why does my array length always turn out to be 0? (I've confirmed that the data is there by using alert on var email). var emails = new Array(); //retrieve all the emails $('.emailBox ...

Is there a way to transform a Base64 image into a specific file type?

Is it possible to integrate my website with an iOS device and utilize the device's camera functionality? After capturing an image, the camera returns it in a base64 image format. Is there a way to convert this to a file type? If the mobile device pr ...

Unable to locate the module 'winston'

Developed a small module that utilizes winston for logging purposes. Installed winston using sudo npm install -g winston (since it's on a virtual machine, not too concerned with sudo permissions). NPM log: <a href="/cdn-cgi/l/email-protection" c ...

Angular 16: ngCharts Error - Unable to Iterate Over registerables Property

ERROR: Uncaught (in promise): TypeError: chart_js__WEBPACK_IMPORTED_MODULE_0__.registerables is not iterable (cannot read property undefined) TypeError: chart_js__WEBPACK_IMPORTED_MODULE_0__.registerables is not iterable (cannot read property undefined) at ...

What is the best way to manage the cumulative index within two nested ng-repeats?

Within the scope of a directive, I am working with two ng-repeats. This directive is responsible for generating a table, and each table cell's data comes from a separate data source. This data source requires the cumulative index of the two repeaters. ...