Organizing an Array of Standard Values into Order

I need to organize a dynamic javascript array that is retrieved from the database each time. The requirement is to sort it based on predefined values in an established order within a standard array.

For example, consider my dynamic array:

var dbArray = ['Apple','Banana','Mango','Apple','Mango','Mango','Apple'];

And let's say the reference array for sorting the above array looks like this:

var stdArray = ['Mango','Apple','Banana','Grapes'];

So, after sorting dbArray according to stdArray, the resulting array should be:

var resultArray = ['Mango','Mango','Mango','Apple','Apple','Apple','Banana'];

This custom sorting approach allows arranging the elements in any desired order specified within stdArray, regardless of traditional alphabetical or other common sorting methods.

Answer №1

This may not be the fastest solution, but it should get the job done

dbArray.sort(function(a,b) { 
    return stdArray.indexOf(a) - stdArray.indexOf(b);
});

If speed is a concern, you could optimize by creating a map to store the index of each item and avoid repeated array scans.

var indexMap ={};
stdArray.forEach(function(str) {
    indexMap[str]=stdArray.indexOf(str);
});

dbArray.sort(function(a,b) { 
    return indexMap[a] - indexMap[b];
});

Answer №2

It is possible to employ a standard sort method and consider the comparison between the position of a and b in relation to your reference array.

dbArray.sort(function (a, b) {
    return stdArray.indexOf(a) - stdArray.indexOf(b);
});

Answer №3

let databaseFruits = ['Apple','Banana','Mango','Apple','Mango','Mango','Apple'];
let standardFruits = ['Mango', 'Apple', 'Banana', 'Grapes'];
let sortedFruits = [];
standardFruits.forEach(function (fruit) {
    while (databaseFruits.indexOf(fruit) !== -1) {
        sortedFruits.push(databaseFruits.splice(databaseFruits.indexOf(fruit), 1));
    }
});
sortedFruits.push(databaseFruits);
console.log(sortedFruits); // Mango, Mango, Mango, Apple, Apple, Apple, Banana,

Answer №4

var dbItems = ['Apple','Banana','Mango','Apple','Mango','Mango','Apple'];

var standardItems = ['Mango','Apple','Banana','Grapes'];

var finalItemsList = new Array();

.

var index, length, count=0, sortCount=0;

for(index=0; index<stdArray.length; index++)
{  
  count = dbArray.filter(function(item){return item==stdArray[index]}).length;
  for(length=0; length<count; length++)
 {
    resultArray[sortCount + length] = stdArray[index];    
 }

 sortCount += count;

}

//CHECK:

var itemsString = "";
 for(index=0; index<finalItemsList.length; index++)
 {
 itemsString += finalItemsList[index];
 itemsString += " ";  

 }

 alert(itemsString);

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

The type 'true | CallableFunction' does not have any callable constituents

The error message in full: This expression is not callable. No constituent of type 'true | CallableFunction' is callable Here is the portion of code causing the error: public static base( text, callB: boolean | CallableFunction = false ...

Show additional information when a row in the Bootstrap Vue table is clicked

I am attempting to create a unique user experience by displaying row details when a row is clicked, rather than clicking on a button as described in the documentation. However, the documentation lacks specific instructions on how to implement this feature. ...

Enhance link with dynamic content using an AJAX call

I need help appending a picture after a link with the same URL as the link. The current AJAX code is producing the following result: <a href="images/Draadloos.png" data-lightbox="gallerij"></a> Here is an example of what I would like to achie ...

One way to filter using a single array

Currently testing some angularJS with this particular example http://www.w3schools.com/angular/tryit.asp?filename=try_ng_filters_filter <ul> <li ng-repeat="x in names | filter : 'i'"> {{ x }} </li> </ul> Is ther ...

Creating Dynamic Tables with jQuery

I have written a code to fetch values using jQuery and Ajax. The data is coming fine but I am facing an issue with populating the rows in my table. The loop doesn't seem to work properly. Here is my HTML table code: <div class="panel-body"> ...

Tips for improving the efficiency of a Solidity smart contract function that removes an element at a specific index within an array

Seeking a more efficient solution, I utilized the following library code to remove an element from an array based on its index. While my current implementation involves using a loop, I am concerned about the high gas costs associated with this approach. ...

How can I use Node.js Express to upload files with Multer?

I am facing an issue while trying to upload a file image using multer in express. The file gets successfully uploaded to the directory, but the name of the file is not being saved in the database. I am utilizing mongodb with express and currently, the file ...

Using JQuery to properly introduce a script in the body of a webpage

<script> /* adjust #splash-bg height based on #meat element */ $(window).on('load',function(){ var splashbgHeight = $("#meat").css("top"); $("#splash-bg").css("height",splashbgHeight); $(w ...

How can Angular be used for live search to provide precise search results even when the server does not return data in the expected sequence?

Currently, I am in the process of constructing a website for one of my clients. The search page on the site is designed to update search results as you type in the search bar - with each keystroke triggering a new search request. However, there's an i ...

Guide on how to capture tweets from particular Twitter profiles

I'm currently experimenting with the twitter npm package to stream tweets from specific accounts, but I'm facing some challenges. After reviewing the Twitter API documentation, I must admit that I am a bit perplexed. To fetch details about a pa ...

Is there a way to automatically organize my XML Link List?

My livesearch feature is functioning well by pulling results from an XML List. However, I have a requirement to include numerous links and I am exploring ways to automate the sorting process alphabetically for convenience. The links need to be arranged fro ...

The bootstrap switch button remains in a neutral grey color

Ordinary: Initially clicked: Click again: After the second click, it remains grey and only reverts on a different action like mouse click or selection. Is there a way to make it go back to its original state when unselected? ...

Navigating through directories using jQuery: Relative versus absolute paths

I'm currently trying to figure out the correct path in jQuery. I have a file called functions.js with a function for loading URLs using jQuery. The issue arises when the JavaScript is loaded on the website's index page but the actual file is loc ...

Controlling the document object model of a third-party website within the Electron framework

I am completely new to electron. My main goal is to load a URL and then execute some Javascript that will make changes to the DOM. Currently, my approach involves creating a BrowserWindow that loads the URL, and I understand that I can utilize webContents ...

Change the value of a particular property in an array of objects by utilizing an inline function

I am working on updating the price field for a specific object. Below is my selectedCurrenciesArray: const [selectedSwapCurrencies, setSelectedSwapCurrencies] = useState([ { symbol: null, logo: null, price: 0 }, { ...

Unlocking the power of event binding in Vanilla JavaScript

Hey everyone, I'm relatively new to JavaScript and have some basic knowledge of jQuery. While browsing through this article on using jQuery in plain JavaScript, I came across the following example: $('a').on('click', fn); In thi ...

Populating a table with information retrieved from a file stored on the local server

Here is the specific table I am working with: <div class="chartHeader"><p>Performance statistics summary</p></div> <table id="tableSummary"> <tr> <th>Measurement name</th> <th>Resul ...

Running function without the need to click on 'li' element

In the process of developing a simple guessing game, my aim is to allow users to click on a number and have that number stored as userAnswer, while the computerAnswer is a randomly generated number between one and ten. Despite setting the setVariables() f ...

Is there a way to overcome the GCM 1000 message limit in order to successfully push notifications to a database of 10,000 recipients?

Currently, I am utilizing the code below for sending GCM messages through PHP and MySQL. I need assistance to modify it so that it can efficiently send GCM messages in batches of 1000 to a database containing 10,000 registered users. Prior to reaching 100 ...

Retrieve the titles of all WordPress posts

I implemented a feature in my Wordpress blog that suggests search results using this code snippet. However, the current setup searches through all tags and I would like it to only search post titles. Any advice on how to achieve this would be greatly appr ...