Tips for organizing the elements of an array according to a specific rule

The array can vary in size but at most it could contain the following elements:

DE/FR/IT/EN/RM

Examples of possible arrays include:

DE/FR/IT/EN/RM,

IT/EN/RM,

DE/RM

and so on.

Is there a way to make an array like this adhere to a specific sorting rule? Specifically, how can I ensure that the array always sorts itself in this order: DE/FR/IT/EN/RM

I attempted to solve this issue with the following code, however, as I am not proficient in JavaScript, I struggle to understand its functionality:

function{
.....
....
...
list.sort(compareList());
...
..
.
}

function compareList() {
    var ruleList = new Array();
    ruleList.push("DE","FR","IT","EN","RM");


}

For example, if the input array contains 3 elements: RM,DE,EN

the sorted output should be: DE,EN,RM

Another scenario is with the maximum 5 elements: FR,DE,EN,RM,IT

which should output:DE,FR,IT,EN,RM

Answer №1

To organize a list based on specific values, you can assign an object with the desired order and a default value for unknown items, then sort the list by calculating the difference between the values. The unknown items will be placed at the end of the list.

function specifyOrder() {
    var order = { DE: 1, FR: 2, IT: 3, EN: 4, RM: 5, default: Infinity };
    return (a, b) => (order[a] || order.default) - (order[b] || order.default);
}

console.log(['RM', 'DE', 'EN'].sort(specifyOrder()));             // DE EN RM
console.log(['FR', 'DE', 'EN', 'RM', 'IT'].sort(specifyOrder())); // DE FR IT EN RM
.as-console-wrapper { max-height: 100% !important; top: 0; }

To maintain the position of the first element in the list, you can assign it a significantly negative value for sorting purposes. This method is effective when the array order is known in advance, as there won't be any index information available for later sorts.

const
    keepFirstElement = (array, sort) => {
        var order = array.reduce((r, v, i) => (r[v] = i + 1, r), { default: Infinity });
        order[array[0]] = -Infinity;
        return array.sort((a, b) => (order[a] || order.default) - (order[b] || order.default));
    },
    order = ['DE', 'FR', 'IT', 'EN', 'RM'];

console.log(keepFirstElement(['RM', 'DE', 'EN'], order).join(' '));             // RM DE EN
console.log(keepFirstElement(['FR', 'DE', 'EN', 'RM', 'IT'], order).join(' ')); // FR DE IT EN RM

Answer №2

var baseLanguages = ["DE","FR","IT","EN","RM"];
var testLanguages = ["DE","IT","FR","EN"];
testLanguages.sort((a,b) => baseLanguages.indexOf(a) - baseLanguages.indexOf(b));
console.log(testLanguages);

The order can be determined by the index of the languages in the base array

var baseLanguages = ["DE","FR","IT","EN","RM"];
var testLanguages = ["DE","IT","FR","EN"];
testLanguages.sort((a,b) => baseLanguages.indexOf(a) - baseLanguages.indexOf(b));
console.log(testLanguages);

Answer №3

To achieve this functionality, you can create a function called sortArrayBy() like the following:

// Custom sorting function for sorting an array based on another array
function sortArrayBy(input, by) {

  var result = [].concat(input)

  result.sort(( str0, str1 ) => {

     const idx0 = by.indexOf(str0)
     const idx1 = by.indexOf(str1)

     // Handling cases where elements are not found in the 'by' array
     if(idx0 === -1) return 1
     if(idx1 === -1) return -1

     return idx0 - idx1
  })
  
  return result;
}

var data = ['DE','FR','IT','EN','RM']

console.log('DE/FR/IT/EN/RM', sortArrayBy(data, ['DE','FR','IT','EN','RM']))
console.log('IT/EN/RM', sortArrayBy(data, ['IT','EN','RM']))
console.log('DE/RM', sortArrayBy(data, ['DE','RM']))

The sortArrayBy() function allows you to specify an order (in the form of the index array by) for sorting the elements in the input array (e.g., ['DE','FR','IT','EN','RM']), producing the sorted array as the result.

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

"Although there are no errors, the ng-switch directive within the ng-repeat is not functioning as

I'm working on setting up a simple image gallery where I can dynamically change the displayed image by setting a specific number for currentImage. Check out my HTML code: <div class="main_image" ng-switch on="current_image"> <img ng-rep ...

Having difficulty retrieving the click event using a jQuery selector

I'm facing issues with my jQuery selector when trying to access a click event. Below is the HTML code snippet: <li class="handle-bars"> <span class="fa fa-bars pull-right text-primary m-t-10"></span> <span class="fa fa-co ...

Choose the option from the jQuery dropdown list based on the displayed text instead of the value

In continuation of my previous question on jQuery getting values from multiple selects together, I am working with a select list like this: <select name="access" class="change" id="staff_off" runat="server"> <option value="8192">Off< ...

I am working with an array of objects in React JavaScript, and I need to find a way to convert it into

Currently, I am in the process of creating this JavaScript function: export function convertArrayObjToFileDownload(data, filename, filetype = 'application/octet-stream') { const blob = new Blob(data, { type: filetype }); downloadBlob(blob ...

What is the significance of incorporating vinyl-source-stream into gulp in my workflow?

Recently, I've been experimenting with gulp and browserify to convert my .jsx files into .js files. var gulp = require('gulp'); var browserify = require('browserify'); var reactify = require('reactify'); gulp.task(&apos ...

Adjust the color of an SVG icon depending on its 'liked' status

In my React/TypeScript app, I have implemented an Upvote component that allows users to upvote a post or remove their upvote. The icon used for the upvote is sourced from the Grommet-Icons section of the react-icons package. When a user clicks on the icon ...

add the array element to the object

How can I extract values from a nested array and push them into a new single object? const Ll = [ { _id: 'milk', category: [ [ { name: 'Alfred', job: 'manager' }, { ...

Enhance user experience with Bootstrap by automatically adding a frame around a card upon clicking

Hello everyone! I am a beginner in the Angular/Web Development world and I am currently working on improving my HTML/CSS skills. While using Bootstrap in my Angular project, I ran into a challenge that I couldn't figure out on my own. I have implement ...

Float two DIVs horizontally with the same height using jQuery

Having a strange issue with the website I'm currently working on and can't seem to figure out what's causing it. Something is definitely off with my javascript, but I just can't pinpoint the exact problem. Here's the situation: I ...

Creating a PHP array using variable dereferencing

I am currently utilizing a recursive function in PHP to navigate through the HTML DOM. My goal is to transform the HTML DOM into a PHP array. <head> <title> My New Web Page </title> </head> <body> <table> & ...

Perform a JSON query using JavaScript

Is there a way to query JSON using JavaScript? In my JavaScript code, I have a JSON stored in a variable called 'json'. This JSON is an array of data, each containing 3 attributes: 'name', 'city', and 'age'. I am in ...

FirebaseError encountered: Unable to update document due to absence of document. Updating document is only possible if document id is hard coded

For my latest project, I have a component that can successfully create a new user and add them to the database using the function createUserWithEmailAndPassword(auth, email, password). Now, I am working on another component that will allow users to edit t ...

Trigger a function upon the initial keypress event detected on an input field

I am facing an issue with an input element that has an onkeypress event triggering a function called change(). Strangely, the function does not execute on the very first keypress. I notice that I have to input 55 instead of just 5 for the function to updat ...

Using jQuery to Delete a DOM Element Once the Ajax Call is Successful

I'm currently facing an issue with removing an element after a successful ajax request. Below is my ajax code snippet: verifyRequest.denyUser = function(requestId,element){ $.ajax({ url: loaderURL+'idverified/denyRequest', ...

Exploring the functionality of Array.prototype.includes() in Angular 7 with PhantomJS testing

While testing components in my Angular application, I noticed that unit tests utilizing Array.prototype.includes() are successful in Chrome but fail when executed with PhantomJS. I found some suggestions in the responses to this question related to a simi ...

Issues with progress loading bars are preventing them from functioning properly on both Chrome and Internet

When I call an ajax method, I have a custom loading bar that works perfectly in Firefox. This is how my code looks: HTML: <div id="loading_dim" > <div></div> </div> CSS : #loading_dim { position: fixed; left:0; ...

Tips for creating an auto-incrementing ID within Firebase's real-time database

How can I create an automatic incrementing ID for entries in a Firebase database? The first item should have an ID of 1, and the second one should be 2. var database = firebase.database(); var userDetails = database.ref("Article"); userDetails. ...

What is the best way to retrieve an ID when parsing JSON recursively?

Could you provide guidance on how to retrieve the IDs of all children when parsing JSON data? I have attempted to use a recursive function, but it seems to be calling infinitely. For reference, here is my code snippet: http://jsfiddle.net/Ds8vQ/ for(var ...

Conceal portion in HTML until revealed

I am attempting to create 3 sections within a single HTML file using the <section id="id"> tag, and I want to be able to open each section by clicking a link in the header with <a href="#id">1</a>, and then close it when another section i ...

Error: Base Conversion causing ArrayOutOfBoundsException

My current project involves converting a number from one base to another, but I keep encountering an ArrayOutOfBoundsException. Can anyone offer some assistance? The number being used is 21, with an original base of 10 and a new base of 2. public static ...