Is the neglected property being discarded?

First things first, let's talk about my class:

class FavoriteFooBar {
 ...
 isPreferred: boolean = false;

 constructor() {
   this.isPreferred = false;
  }
}

Using a utility library called Uniquer, I arrange a list of FavoriteFooBar instances to prioritize favorites at the top:

this.favFBBars = Uniquer.orderBy(this.favFBBars, ['isPreferred', 'name'], ['desc', 'asc']);

After marking an item as favorite and checking my console log, it shows:

https://i.sstatic.net/4ogPm.jpg

Note that #3 does not have the isPreferred property...

It seems like Lodash doesn't sort properly when isPreferred isn't explicitly set. Is there a way to always display this property, even if it's unused/unset/false?

I've already tried:
- Initializing the property to false in the class
- Setting the property to false in the constructor of the class
- Iterating through this.favFBbars in the component and setting them all to false
- Implementing an interface for FavoriteFooBar

Answer №1

It appears that this is the TypeScript approach to setting a default value for a class property.

export default class FooBar {
  constructor(private isFavorite: boolean = false) {
     ...
  }
}

Alternatively, you can achieve the same result with the following code:

export class FooBar {
  constructor() {
     this.isFavorite = false;
  }
}

If you want to sort a list based on a specific condition, you can use a function in the _.orderBy iteratee like this:

var foobars = [{isFavorite:false, name:"aaa"}, {isFavorite:true, name:"bbb"}, {isFavorite:false, name:"ccc"}, {name:"ddd"}]


foobars = _.orderBy(foobars, [function(foobar) {
    return foobar.isFavorite == true;
}, "name"], ["desc", "asc"]);

console.log(foobars)
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aec2c1cacfddc6ee9a809f99809f9e">[email protected]</a>/lodash.min.js"></script>

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

Limit the Jquery selection specifically to elements on the modal page

Recently I encountered an issue with a webpage that opens a modal form. The problem arises when the validation function, written in JQuery, checks all fields on both the modal and the page beneath it. //validate function function validateFields() { v ...

Retrieving queries from a sibling component using react-query: A step-by-step guide

I have a question regarding how to refetch a query from another sibling component using react-query. Let's consider Component A: import {useQuery} from "react-query"; function ComponentA(){ const fetchData = async () => data //re ...

Customizing the Material UI v5 theme with Typescript is impossible

I'm attempting to customize the color scheme of my theme, but I am encountering issues with accessing the colors from the palette using theme.palette. Here is a snippet of my theme section: import { createTheme } from "@mui/material/styles&qu ...

JavaScript random number functionality experiencing an unexpected problem

function generateRandomNumbers(){ var max = document.getElementById('max').value; var min = document.getElementById('min').value; var reps = document.getElementById('reps').value; var i; for (i=0; i<reps ...

Exploring a JSON with multiple sectioned pages

I have developed a script that loops through a multi-page JSON object. def get_orgs(token,url): part1 = 'curl -i -k -X GET -H "Content-Type:application/json" -H "Authorization:Bearer ' final_url = part1 + token + '" ' + url ...

Exploring the capabilities of utilizing filters within a ternary operator in AngularJS

Can a filter be applied to a variable in the template within a ternary operation? <img ng-src="{{ image_url && image_url|filter:"foo" || other_url }}"> In this scenario, the filter is custom-made and I prefer not to alter it to accommodate ...

Developing an Angular 11 Web API Controller with a POST Method

I am in need of creating or reusing an object within my web API controller class to send these 4 variables via a POST request: int Date, int TemperatureC, int TemperatureF, string Summary Currently, I am utilizing the default weather forecast controller t ...

Axios displays a status code of 0 instead of the expected 403

Trying to monitor the responses of requests using axios response interceptors has been quite a challenge for me. In one specific request that necessitates authorization, everything goes smoothly when the token is valid, and data is returned without any is ...

Issue with Caching during Javascript Minification

I Have ASP.Net MVC 3 App. Utilizing YUICompressor.Net for compressing Javascript and CSS files post build with MSBuild. The minimized javascript file is named JSMin.js and the CSS file is CssMin.css. In my master page, I reference these files as shown bel ...

Displaying JSON keys and values individually on an HTML page

Looking to display a JSON array in HTML using ngFor TypeScript : import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-ng-for', templateUrl: './ng-for.component.html', styleUrls: ['./ng-for ...

The error message "In a Flutter application, trying to cast a 'List<dynamic>' to a 'List<int>' is not valid as they are not compatible subtypes."

Upon running the main.dart file within a Flutter app, an exception is being encountered. The code in question reads data from a data.json file and attempts to map it into a SubTypeMap class, followed by a TypeMap class. Could anyone provide insight into w ...

Creating stylish rounded corner bars using angular-google-charts

Currently, I'm utilizing angular-google-charts in one of my projects and I have a specific need to create a column chart with rounded corners. https://i.stack.imgur.com/rvJ2H.png Is there a method to achieve this using angular-google-charts? .ts fi ...

I am noticing that my popover is causing my page to shift when I click it. It is expanding the width of my page more than I would

Upon clicking the user id popover on my page, it expands the page width instead of adjusting within the page boundaries. This is the issue: https://i.stack.imgur.com/EqaMo.png There's a small white space present that I want to eliminate. When the po ...

What is the method to incorporate a fresh generic parameter without officially announcing it?

My goal is to define a type union where one of the types extends an existing type: // The original type type Foo<V> = { value: V; onChange: (value: V) => void }; // Type union incorporating Foo type ADT = ({ kind: "foo" } & Foo<a ...

Enroll in a stream of data while iterating through a loop in an Angular application

I encounter a situation where I must subscribe to an Observable, iterate through the response, and then subscribe to another Observable using data from the initial Observable. getTasks(taskType: Observable<any>): void { taskType // Subscribing ...

Tips for moving a texture horizontally across a sphere using threejs

I have a 360 degree viewer tool. Is there a way to load a texture in a specific position that will rotate the original image by a certain number of degrees or units around the Y-axis without altering anything else about how the picture is displayed? If s ...

Unable to retrieve the sum total of all product items and display it in the designated text element

My product items are dynamically generated in a list. I have used the calculateItemTotal() method to determine the total for each item. Now, I need to sum up all these item totals and display the result in the total text field. However, instead of showing ...

Angular: undefined value detected during NgOnInit execution

Although the topic has been discussed, I am unable to find a solution to my specific issue. The problem lies in my parent component that returns data passed to an input. Parent component TypeScript: public productList!: IDocumentProduct[]; constructo ...

The process of compressing font files (such as ArialMT.ttf) using JSZip is experiencing issues

While zipping images and HTML files works smoothly, I encountered an issue when trying to add font files for CSS. The font file is only 1kb in size, but it cannot be opened. Even after attempting to zip the font without any other files, the problem persis ...