Sorting by two fields with varying value types in AngularJS

Need help sorting json data by two fields, prioritizing field value and then date.

Check out this demo

Json input

[{
"title" : "Title 2",
"pin"   : false,
"date" : 20130411204207
},{
"title" : "Title 3",
"date" : 20140411204207
},{
"title" : "Title 4",
"date" : 20120411204207
},{
"title" : "Title 1",
"pin"   : true,
"date" :  20100411204207
}]

I aim to prioritize objects with "pin : true" first, followed by descending order of "date". Using "orderBy" method, any alternatives?

http://jsfiddle.net/tomalex0/tvLUK/1/

Output json

[
{
    "title": "Title 1",
    "pin": true,
    "date": 20100411204207
},
{
    "title": "Title 3",
    "date": 20140411204207
},
{
    "title": "Title 2",
    "pin": false,
    "date": 20130411204207
},
{
    "title": "Title 4",
    "date": 20120411204207
}
]

Answer №1

To achieve functionality, transform the pin into a numerical value using the following code:

$filter('orderBy')($scope.sorted, ["0 + !!pin", "date"], true);

I have modified your fiddle to include a functioning version

Answer №2

If you're looking to improve your sorting technique, consider implementing a sort expression similar to the one shown below:

 $scope.sortValues = function (){
    var sortedValues = $filter('orderBy')(dataArray, ["pin == undefined ? -1 : (pin ? 1 : 0)","date"], true);
    console.log(sortedValues);
}

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 can I intercept/manage the back button of the browser in React-router?

Utilizing Material-ui's Tabs, which are controlled, I am implementing them for (React-router) Links in the following manner: <Tab value={0} label="dashboard" containerElement={<Link to="/dashboard/home"/>}/> <Tab value={1} label="users ...

Tips for inserting user input into an array and showcasing it

const [inputValue, setInputValue] = useState(""); return ( <input onChange={(event) => setInputValue(event.target.value)} /> <p>{inputValue}</p> ); I'm facing a problem where I need to take input from a user and store it in ...

Having trouble deciphering this snippet of Express JS source code

Upon reviewing the Express JS source code, I came across the main module where express is being exported. module.exports = createApplication; function createApplication() { var app = function(req, res, next) { app.handle(req, res, next); }; m ...

Encountering a series of errors in Discord.js v14 while executing a specific

UPDATE :- After troubleshooting, I discovered that the previous error stemmed from my command handler itself! However, now I am encountering a whole bunch of new errors... actually, multiple errors. So, I'm in desperate need of assistance. (Note: Apol ...

A Comprehensive Guide: Obtaining the Final Tab from a JSON using API

What is the method to extract the last tab from a given JSON code? { "claimed_levels": { "level_1", "level_2" } } I want to display the level when someone types "!levels". The desired output format should be: Your current level is "2" ...

What is the best method in typescript to combine objects in an array with identical properties but varying values?

interface IData{ cabinTo:string[]; cabinFrom:string; } const dataAfterIteration= [{cabinTo:"A",cabinFrom:"B"}, {cabinTo:"A",cabinFrom:"C"}, {cabinTo:"B",cabinFrom:"C"}, { ...

Unable to load the .js file within the Angular module

I am facing an issue with my Angular sidebar component that is trying to load a local script called sidebar.js. I have the following code in src\app\sidebar\sidebar.component.ts: ngAfterViewInit(): void { const s = document.createEleme ...

The magnifying glass icon is missing from the autocomplete search feature

After creating an autocomplete search functionality that queries my mysql database, I encountered a slight issue. Here is the code snippet showcasing my implementation: <div class="search-bar"> <div class="ui-widget"> <input id="ski ...

The eval() function does not run scripts from external sources with a src attribute

Instead of using eval() to execute all <script> tags after completely rewriting a div, I have encountered an issue. The following code snippet works for inline-scripts, but it doesn't have the same effect on external scripts like: <script sr ...

Sharing data between two PHP pages via an AJAX request

On my webpage, specifically on page 1.php, I am saving a variable to an input field text. Name:abc Done. After clicking the 'done' button, the name abc is sent to another page called 2.php via an Ajax request. In 2.php, I am storing the value ...

The power duo of Jasmine and Angular: unleashing the potential of

My Angular application has defined constants for the application like so: var module=angular.module('abc'); module.constant('constants',{ INTERNAL_VALUE:1 }); Within my controller, I have the following code: if(someService.getInter ...

Sequelize Error: Cannot call User.hasMany as a function

I am experiencing a strange issue with my User and Client models. The User model has a relationship with the Client model, where User has many Clients. I am currently referencing the Sequelize documentation for associations at this link: Upon running the ...

Incorporate JavaScript to enable the transfer of text from one textarea to another upon clicking a button, while simultaneously clearing the original textarea

After working on the provided code, I have managed to create a functionality where text from one textarea is copied to another textarea when a button is clicked using JavaScript. <head> <script type="text/javascript"> function displayOut(){ ...

Issue with Jquery Conflict in WordPress

Apologies if my inquiry is not up to standard. I am currently utilizing a Google library in my project. <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> The issue arises when this conflicts with the jQuery u ...

Implementing pagination in a Node.js application using MongoDB.ORCreating

function implementPaginationForDigitalMigrationJoin(req, res, next) { DigitalMigrationForm.aggregate([ // Join with user_info table { $lookup: { from: DigitalMigrationFormList.collection.name, // other ...

Tips for emphasizing the currently pressed button element when clicked in Angular 2?

Here is the code snippet I am currently working with: <button *ngFor="let group of groupsList" attr.data-index="{{ group.index }}" (click)="processGroups(group.index)">{{ group.title }}</button> I am trying to figure out if it is possible to ...

Invoke a handler from one function within another function

I am unsure of the best approach for achieving this, or if it is even feasible, but I have two components: a main navigation bar (NavBar) that spans across the top of the page, and a sidebar drawer. NavBar: export default function NavBar() { const c ...

Having trouble getting the onClick event to trigger in ReactJS buttons

The buttons are not functioning as expected, allowing for the addition of positive, neutral, or negative feedback. Interestingly, when I added a default button using different syntax to add negative feedback, it worked. This suggests that there may be an ...

Can anyone help me find the Ajax URL for October CMS?

I'm interested in implementing Angular JS with October CMS. Can someone guide me on how to send data to the controllers via a POST request? Upon digging through the October framework.js file, I came across this code snippet: headers: { 'X-O ...

Using Highmaps in a VueJs application involves passing a state to the mapOptions for customization

I'm currently struggling with passing a vuex state to mapOptions in vuejs components. Here is the code snippet: <template> <div> <highcharts :constructor-type="'mapChart'" :options="mapOptions" class="map">&l ...