Arrange a collection of words in alphabetical order based on word importance

Given the array below

[
  { name: '4K UHD', commentator: 'Ali' },
  { name: 'English 1 HD', commentator: 'Ahmed' },
  { name: 'English 3 HD', commentator: 'Ahmed' },
  { name: 'Premium 1 HD', commentator: 'Ali' },
  { name: 'Premium 2 HD', commentator: 'Ahmed' },
]

I need to organize it so that objects with a name containing Premium are at the beginning in ascending order.

The expected output is as follows

[
  { name: 'Premium 1 HD', commentator: 'Ali' },
  { name: 'Premium 2 HD', commentator: 'Ahmed' },
  { name: '4K UHD', commentator: 'Ali' },
  { name: 'English 1 HD', commentator: 'Ahmed' },
  { name: 'English 3 HD', commentator: 'Ahmed' },
]

// or like this
[
  { name: 'Premium 1 HD', commentator: 'Ali' },
  { name: 'Premium 2 HD', commentator: 'Ahmed' },
  { name: 'English 1 HD', commentator: 'Ahmed' },
  { name: 'English 3 HD', commentator: 'Ahmed' },
  { name: '4K UHD', commentator: 'Ali' },
]

Answer №1

Utilize a customized comparison function to achieve the desired sorting results

const customSort = (x, y) => {
    const px = x.title.startsWith("Special");
    const py = y.title.startsWith("Special");
    return 
        px !== py 
          // if comparing Special vs non-Special, Special takes priority
        ? (px ? -1 : 1) 
          // for everything else within the same category
        : x.title.localeCompare(y.title); 
};

dataList.sort(customSort);

Arrange all items starting with Special at the beginning of the sort, maintaining order within the separate categories.

Answer №2

Experiment with a different approach:

arrangement.sort((x, y) => x.value < y.value ? 1 : -1)

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

Disable the ng-change event

Is there a way to prevent the ng-change event from happening? I have a select box with an option that I don't want users to select. Instead, I want to display a warning message and then revert back to the previously selected option. To achieve this, ...

In JavaScript, when using the fetch function with JSON, it is possible to skip the

Here's an example of fetching review data from within a 'for loop': fetch('https://api.yotpo.com/products/xx-apikey-xx/{{product.id}}/bottomline') In this case, some products may not have reviews and will return a 404 response. Th ...

Having trouble obtaining the serialized Array from a Kendo UI Form

I am working on a basic form that consists of one input field and a button. Whenever the button is clicked, I attempt to retrieve the form data using the following code: var fData = $("#test").serializeArray(); Unfortunately, I am facing an issue where I ...

Illuminate specific areas of a mapped image upon hovering over text on a webpage

Scenario: There is an image on the page with various mapped areas. A list of text elements is also present on the page. Desired functionality: Hovering over different text items in the list should result in highlighting corresponding areas on the mappe ...

What exactly does "blocking and tackling" refer to in the Angular2 documentation?

As I delved into the online documentation for angular2, I stumbled upon a puzzling term - "blocking and tackling" in the ADVANCED - Angular Module chapter (https://angular.io/docs/ts/latest/guide/ngmodule.html). ... "It's all just basic blocking and t ...

What exactly is the concept of lazily installing a dependency?

The website here contains information about the changes in Ember 2.11. Ember 2.11 now utilizes the ember-source module instead of the ember Bower package. In the upcoming Ember CLI 2.12 release, Bower will no longer be installed by default but will only ...

Issue with the demo code for Vue Stripe Checkout

As I delve into the world of Vue-Stripe-Checkout, I encountered a snag right from the start with the demo code provided. The issue arises when utilizing the Vue Stripe Elements component. Has anyone else experienced this problem? There are no errors displa ...

Can we condense the code to create a more concise and efficient function?

Can someone help me refactor this code snippet below into a function and combine the two IF statements? Many thanks! let value = productDetails.recentPurchaseDate; if (!productDetails.salesPrice && !productDetails.recentPurchaseDate) { value = false; } ...

Enhancing Angular with Plotly: Implementing click events on bar chart legends

I'm currently working on implementing color pickers for my plotly-plot charts within an Angular template. I am looking to add a function that triggers when the chart legend is clicked. How can I achieve this and get a click event for the chart legends ...

I am attempting to iterate through a multidimensional array using a foreach loop

$details = array( array( 'name' => 'Ahmed', 'age' => 24, 'hobbies' => array('swimming','Drawing','Programming') ) ); The desired final re ...

Updating MongoDB collections in Mongoose with varying numbers of fields: A step-by-step guide

Updating a mongodb collection can be challenging when you don't know which fields will be updated. For instance, if a user updates different pieces of information on various pages, the fields being updated may vary each time. Here is my current appro ...

Shuffle the contents of various div elements, conceal one, reveal another

I am currently working with a menu that uses the loadContent function to load pages into the #main div. This allows me to change the content of the page while keeping the menu intact. <ul> <li class="page1" onclick="loadContent('page1.php ...

Not all dynamic content is loaded through Ajax requests on a single domain

I currently have my domain forwarded (cloaked) to The main page (index.html) utilizes Ajax for loading content. All content loads properly at the original host (moppy.co.uk/wtcdi). However, on the forwarded domain (whatthecatdragged.in), some content fai ...

Unable to retrieve Google Maps route on Android device

After discovering the route between two latitude and longitude values on Google Maps using "Get Directions," everything appears accurately. However, when attempting to use the same directions in an Android mobile application, only the destination marker ...

Tips for sending multiple forms and having PHP interpret it as a single form using $.ajax

I am working on an email function using $.ajax with 3 different forms that are loaded through an ajax request. When a user clicks on a button, the current form will disappear and a new form will appear. The challenge I am facing is how to send data from al ...

Updating the title of a page on CoreUI's CBreadcrumbRouter dynamically

I'm currently developing a project with VueJS and the CoreUI admin template. Is there a way I can change the title of the current page as shown on the CBreadcrumbRouter? The GitHub documentation mentions that the script typically displays meta.label ...

Arranging a list based on the child property in a React component

Within my application, I have an array mapped to a map that generates a div with a data-date attribute as shown below: It's worth noting that the array cannot be sorted here since there are no dates available for comparison, only the element ID cons ...

The color used to highlight questions on Stackoverflow

Could someone please help me identify the specific color that stackoverflow uses to highlight the background when a question answer link is followed? For instance, take a look at this link: Is there a float input type in HTML(5)? Appreciate any assistanc ...

Implementing the SendOwl License API for theme licensing

Currently developing a Shopify theme for sale and exploring licensing options Considering using SendOwl's API for licenses - Shopify themes support html/css/js/liquid, no server-side code, so JavaScript is required. Can the SendOwl API be used to v ...

Delving into the intricacies of mongoose

Good day, I am struggling with a problem while trying to set up a cart field within the user object. To be more specific, I have created a basic model: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const userSchema = new S ...