Arranging an array in alphabetical order, with some special cases taken into consideration

Below is a breakdown of the array structure:

[{
    name: "Mobile Uploads"
  }, {
    name: "Profile Pictures"
  }, {
    name: "Reports"
  }, {
    name: "Instagram Photos"
  }, {
    name: "Facebook"
  }, {
    name: "My Account"
  }, {
    name: "Twitter"
  }]
  

The goal is to rearrange the array so that it starts with Profile Pictures, followed by Mobile Uploads, Instagram Photos, and then the remaining objects sorted in alphabetical order.

Answer №1

To achieve the desired outcome, create an object specifically designed to handle sorting exceptions. Afterwards, develop a custom sort() function that takes into consideration these exceptions.

var list = [{
  name: "Date"
}, {
  name: "Mobile Uploads"
}, {
  name: "Profile Pictures"
}, {
  name: "Fig"
}, {
  name: "Instagram Photos"
}, {
  name: "Cherry"
}, {
  name: "Apple"
}, {
  name: "Banana"
}];

var exceptions = {
  "Profile Pictures": 1,
  "Mobile Uploads": 2,
  "Instagram Photos": 3
}

list.sort(function(a, b) {
  if (exceptions[a.name] && exceptions[b.name]) {
    // Handle cases where both items are exceptions
    return exceptions[a.name] - exceptions[b.name];
  } else if (exceptions[a.name]) {
    // If only `a` is in exceptions, move it to the front of the list
    return -1;
  } else if (exceptions[b.name]) {
    // If only `b` is in exceptions, move it to the back of the list
    return 1;
  } else {
    // No exceptions found, perform a standard alphabetical sort
    return a.name.localeCompare(b.name);
  }
});

console.log(list);

Answer №2

    var sortingAlgorithm = [{
        name: "Mobile Uploads"
     },
     { 
        name: "Zeta"
     },
     {
        name: "Beta"
     },
     {
        name: "Alfa"
     },
     { 
        name: "Profile Pictures"
     },
     {
        name: "Instagram Photos"
     }]

var compareFunction = function(a,b){
    var weightTable = {"Profile Pictures":1, "Mobile Uploads":2, "Instagram Photos":3}
    ,   nameA = a.name
    ,   weightA = weightTable[nameA] || 100
    ,   nameB = b.name
    ,   weightB = weightTable[nameB] || 100

    if(weightA != weightB){
        return weightA - weightB;
    }else{
        return nameA > nameB;
    }

}

console.log(sortingAlgorithm.sort(compareFunction));

Using weights for sorting management.

Answer №3

One effective approach is to utilize a custom sort function for sorting arrays. The sort callback function takes two arguments - the first and second elements of the array being compared. Within the callback body, you can implement any logic to determine the comparison result. Returning -1 indicates that the first element should precede the second, 1 means the opposite, and 0 implies equality between the elements.

For alphabetical sorting, compare strings using operators like <, >, <=, or >=. Depending on desired order (ascending or descending), return either -1 or

1</code. To optimize for duplicate items in large data sets, returning <code>0</code can help maintain performance.</p>

<p>To introduce exceptions in alphabetical sorting, assign unique numeric representations to elements. Negative numbers signify exception cases, with smaller values indicating priority. Utilize an if statement to identify and handle exceptions during sorting.</p>

<p><div>
<div>
<pre class="lang-js"><code>    

var inputArray = [{
  name: "Mobile Uploads"
}, {
  name: "Profile Pictures"
}, {
  name: "Reports"
}, {
  name: "Instagram Photos"
}, {
  name: "Facebook"
}, {
  name: "My Account"
}, {
  name: "Twitter"
}];

var sortedArray = inputArray.slice(0); // create copy for non-destructive sorting
sortedArray.sort(function(a, b) {
    var aIndex = 0,
        bIndex = 0;
    switch (a.name) {
        case "Profile Pictures":
            aIndex = -3;
            break;
        case "Mobile Uploads":
            aIndex = -2;
            break;
        case "Instagram Photos":
            aIndex = -1;
            break;
    }
    switch (b.name) {
        case "Profile Pictures":
            bIndex = -3;
            break;
        case "Mobile Uploads":
            bIndex = -2;
            break;
        case "Instagram Photos":
            bIndex = -1;
            break;
    }
    if (aIndex < 0 || bIndex < 0) {
        return aIndex < bIndex ? -1 : 1; 
    } else {
        return a.name < b.name ? -1 : 1;
    }
});

console.log('Before:');
console.log(inputArray.map(function(v) {
    return v.name;
}).join(', '));

console.log('After:');
console.log(sortedArray.map(function(v) {
    return v.name;
}).join(', '));

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

I am facing an issue where this loop is terminating after finding just one match. How can I modify it to return

I am currently working with an array that compares two arrays and identifies matches. The issue is that it only identifies one match before completing the process. I would like it to identify all matches instead. Can anyone explain why this is happening? ...

Guide to Embedding an Image in a List in HTML

How do I resize an image according to the size specified in CSS, and ensure that it fits within a list of items where each item consists of both an image and a name? Currently, my code only displays the image in its original size. for(var i =0; i< o ...

Retrieving the selected date from mat-datepicker into a FormControl

When creating a POST request to an API, I encountered an issue with the mat-datepicker field as it throws an error when inside the ngOnInit() call (since nothing is selected yet). Other fields like name, email, etc. work fine, but extracting a value from t ...

Is it possible to resend an AJAX request using a hyperlink?

Is it possible to refresh only the AJAX request and update the content fetched from an external site in the code provided below? $(document).ready(function () { var mySearch = $('input#id_search').quicksearch('#content table', ...

Creating dropdown menus dynamically and populating them based on the selection made in one dropdown menu to determine the options available

Looking to enhance the filtering options in my ngGrid, I stumbled upon the concept of Filtering in Ignite UI grid and was impressed by its functionality. I am now attempting to implement a similar feature in AngularJS. Breaking down the task into 4 compon ...

unusual behavior observed in addEventListener

I have recently delved into learning about the DOM. I have a project in mind where I want to create a website with buttons that, when clicked, play different drum sounds. As part of my experimentation with JavaScript, I wanted to explore the this keyword. ...

Headers cannot be set again after they have been sent to the client in Express Node

I attempted to create a post request for login with the following code: router.post('/login', async(req, res) =>{ const user = await User.findOne({gmail: req.body.gmail}) !user && res.status(404).json("user not matched") c ...

What is causing this console to output twice?

My Objective: I aim to utilize Node.js to launch two child processes sequentially at a specific time, displaying their `stdout` as it streams, occasionally alternating between the two processes. The Desired Output: `Proc 1 log # 1` `Proc 1 log # 2` `Pr ...

Extracting a precise data point stored in Mongo database

I have been struggling to extract a specific value from my MongoDB database in node.js. I have tried using both find() and findOne(), but I keep receiving an object-like output in the console. Here is the code snippet: const mongoose = require('mongoo ...

Tips for sending dynamic column and row information to antd table

https://i.sstatic.net/XY9Zt.png The following code does not seem to work for an array containing rows and columns Below is an example using antd: const data = []; for (let i = 0; i < 4; i++) { data.push({ key: i, name: `Edward King ${i}`, ...

Using this functionality on a ReactJS Functional Component

Hey everyone, I'm fairly new to using React and I'm currently trying to wrap my head around some concepts. After doing some research online, I stumbled upon a situation where I am unsure if I can achieve what I need. I have a functional componen ...

Use the ngFor directive to iterate over the most recently created array from the parent ng

I am looking to link material tabs with ngFor to generate arrays for child ngFor. Let's start from the beginning: <mat-tab-group> <mat-tab *ngFor="let tab of asyncTabs "> <ng-template mat-tab-label>{{tab.label}}</ng-template ...

Error in Vue.js 2 Composition API: Trying to access 'length' property of undefined object

Greetings to the Vue.js user community! I'm facing a challenging issue that I can't seem to resolve: I am currently using Vue.js 2.x on Windows 11. Whenever I run yarn install or npm install, I encounter an error as displayed in the console. Vi ...

Utilize React to iterate through a dictionary and display each entry

Essentially, I am pulling data from my API and the structure of the data is as follows: { "comments": [ { "user": "user1" "text": "this is a sample text1" }, { "user": "user2" "text": "This is a simple text2" }, } ...

What is the best way to assign JSON data to a Class variable within Angular?

In my code, I have a class called Projects export class Projects { project_id: number; project_name: string; category_id: number; project_type: string; start_date: Date; completion_date: Date; working_status: string; project_info: string; area: string; add ...

Nested ng-repeats within ng-repeats

I have a question regarding the correct way to utilize an inner ng-repeat inside of an outer ng-repeat: Essentially, I am looking to implement something along these lines: <tr ng-repeat="milestone in order.milestones"> <td>{{mi ...

Javascript handling scrolling and repositioning

When using the scrollBy() method in the window object of JavaScript, there are two arguments required. But what do these arguments actually represent? The resource I am currently studying from states that it is "the number of pixels to scroll by," but I am ...

Does Node Express call the next middleware immediately when the next function is called?

Can someone please help me grasp the concept of how the next function operates within the Node Express framework? I know that we utilize the next function within the current middleware to trigger the execution of the subsequent middleware listed. These mid ...

Testing an Express application using Jenkins

After spending hours searching for a way to execute my Mocha unit tests in Jenkins for my Express JS application, I am still struggling to find a solution. While writing the tests themselves is relatively easy, integrating them with my app has proven to b ...

The state of XMLHttpRequest always remains in a perpetual state of progress, never

I have come across an MVC Core application. One of the methods in this application currently has the following structure: public IActionResult Call(string call) { Response.ContentType = "text/plain"; return Ok(call); } In addi ...