order by truthiness

I am working with an array of the following class:

export class Tests {
  id: number;
  name: string;
  createdAt: any;
  succress: boolean;

  constructor(id: number, name: string, createdAt: any, success: boolean) {
    this.id = id;
    this.name = name;
    this.createdAt = createdAt;
    this.succress = success;
  }
}

My goal is to sort the array based on the value of the success property (false should be on top and true on bottom). How can I achieve this?

I attempted the following:

this.tests.sort((a,b)=> b.succress - a.succress);

However, this code is not having any effect. Can anyone help me figure out the issue?

Answer №1

To sort by a boolean value, you can use the following method:

this.items.sort((x, y) => {
   if (x.completed === y.completed) {
      return 0;
   }

   if (x.completed) {
      return -1;
   }

   if (y.completed) {
      return 1;
   }
});

Answer №2

Perhaps this could work?

[true,false,true,false]
.sort(
  (x,y)=>
    (x===y)?0
    :(x===true)?-1:1)

Answer №3

If you want to sort a list based on a specific key, you can make use of the powerful lodash sortBy function.

_.sortBy(this.data, ['priority'])

For a live demonstration, check out this LIVE DEMO.

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 enigmatic occurrence of TypeScript decorators: when a decorator parameter mysteriously transforms into undefined in a particular scenario

I have been working on developing my own Object-Relational Mapping (ORM) system and I encountered an interesting issue in TypeScript that I am trying to understand. If anyone can provide some insight or clarification on this matter, it would be greatly app ...

Tips for sending an array of any type to a Lookup function

I'm currently utilizing ngl-lookup from the ngl-lightning library and I'm attempting to pass an array of type any[] instead of String[]. Here's the code snippet I have: <ngl-lookup [lookup]="lookupManagerUsers" [icon]="true" [image]="&a ...

Different types of subscriptions for forkJoin observable

I am currently making two API requests with typed responses and combining them using the Observable.forkJoin method. My goal is to store each of the results in separate typed variables. var observableOrganization: Observable<Organization> = this.get ...

Utilizing Angular to call a function defined in Renderer2 and assign it to a

In my directive, I have configured a table value to be replaced by an anchor tag using the renderer.setProperty method. The anchor tag is enhanced with a "click" attribute that I am unsure how to interact with: either through accessing the function "onCli ...

Exploring Deeply Nested Routing in Angular

I've been exploring the use of multiple router outlets and encountered an issue. When using the navigateBy function of the router, I am unable to view my child route and encounter an error. However, when I access it via the routerLink in HTML, I get ...

When you use Array.push, it creates a copy that duplicates all nested elements,

Situation Currently, I am developing a web application using Typescript/Angular2 RC1. In my project, I have two classes - Class1 and Class2. Class1 is an Angular2 service with a variable myVar = [obj1, obj2, obj3]. On the other hand, Class2 is an Angular2 ...

The service.subscribe function in Angular's Component Constructor is not functioning properly after the update

There are two components in my project, a parent and child component, and I am using a shared service to transfer data between them. The structure of the Service Class is as follows: export class AddItemDataTransferService { // Observable string sourc ...

The initial execution of the "ionViewDidEnter" method in Ionic 2 can be quite sluggish

Could you explain to me why there is a significant delay in loading the below functionality for the first time, but it loads normally on the second attempt? The same delay occurs on the actual device as well. Please refer to the attached video. Note : The ...

Error: In Typescript, it is not possible to assign the type 'false' to type 'true'

Currently, I am exploring Angular 2 and encountered a situation where I set the variable isLoading to true initially, and then switch it to false after fetching required data. However, upon executing this process, I encountered the following error message: ...

Try out NextJS API middleware by running tests with Jest

I have a middleware setup in my NextJS API route, located at /src/middleware/validateData/index.ts. It's used to validate request data using a schema. import { NextApiRequest, NextApiResponse } from 'next'; import schema from './schema ...

Injecting Dependencies in Angular 2 Without Using the Constructor

Exploring DI in Angular 2 has led me to implement a REST-Client using generic subtypes for concrete Datatypes like this: class RESTClient<T>{ constructor() { var inj = ReflectiveInjector.resolveAndCreate([HTTP_PROVIDERS]); this. ...

Tips for customizing the CSS of a child component that has been imported from a different module in Angular 2

I have been using agm-snazzy-window from amg-snazzy-window There is a mention that I can modify the css class, but when I try to do so, it doesn't seem to work. Here is an example: map-component.html <agm-snazzy-info-window [closeWhenOthersOp ...

Angular 2: Triggering the "open" event for a Bootstrap dropdown

I am currently in the process of developing a directive that will trigger a Bootstrap dropdown to open when clicked and close it when the mouse leaves. Below is the code for the dropdown directive: import {Directive, HostBinding, HostListener} from ' ...

Angular 2 is having trouble identifying a component that was imported from a module

Exploring the functionalities of Angular2, I am attempting to have one module (BreadcrumbDemoModule) import the component from another module (BreadcrumbModule). At the moment, the BreadcrumbModule consists of only one component: ng2-breadcrumb. However, ...

Creating a TypeScript generic record with specified keys

I need to validate in TypeScript whether an object contains the specified keys (from SingleShopColumns or MultishopColumns) and has a validations property that is an array of strings. I am using Record and generics, but any simple method of representing t ...

Angular 10 library devoid of ivy technology

After successfully building an Angular 10 library and using it via a direct import (file:dist/my-lib), I decided to publish the library to a private npm repository. To accomplish this, I made changes to my tsconfig.lib.json file and disabled ivy: "ang ...

Discovering specific values for an ID using API calls in Angular (Implementing CRUD Operations in Angular with API Integration)

My current project involves CRUD operations in Angular utilizing the API created in Laravel. I have successfully added and fetched values, but encountered an issue when attempting to update values using their respective IDs. This snippet is from my app.co ...

Issue with Async pipe when utilizing autocomplete functionality

HTML Code <mat-form-field> <input type="text" matInput class="formControl" [formControl]="name" [matAutocomplete]="auto" > <mat-autocomplete #auto="matAutocomplete"> <mat-option *ngFor="let option of city | async" [valu ...

RxJS Transformation is failing to return the updated object

In my Angular 5.1 single page application, I am encountering an issue with a service response while calling REST services. The problem lies in how the response is handled when it returns an array of Events. Here is how I am trying to transform the response ...

Ways to generate arrays in Typescript

My dilemma lies in a generator method I've created that asynchronously adds items to an array, and then yields each item using yield* array at the end of the process. However, TypeScript compiler is throwing me off with an error message (TS2766) that ...