Perform the subtraction operation on two boolean values using Typescript

I'm working with an array:

main = [{
           data: x,
           numberField: 1;
 }, {      data: y,
           numberField: 2;
 }, {      data: x,
           numberField: 3;
 },
  {        data: z,
           numberField: 4;
 },
    {      data: q,
           numberField: 5;
 }]
fixedElements = [3, 5]

My goal is to achieve the following:

 fixedElements.includes(a.numberField) - fixedElements.includes(b.numberField) 

The purpose of this comparison is to determine if two incoming values are present in array a without sorting them, but sort the remaining elements. However, TypeScript throws an error when attempting this operation.

 left/right-hand side of the argument needs to be of type any or number.

Initially, my sorting function looks like this:

 sort(a,b) {
  if(a.numberField > b.numberField)
       return -1

  if(a.numberField < b.numberField)
     return 1;

    }

As I wanted to prioritize checking if a or b are part of the fixedElements array and position them last. Is there a better way to approach this?

Answer №1

To convert booleans to numbers, use the + sign (demo on typescript playground):

+fixedElements.includes(a.numberField) - +fixedElements.includes(b.numberField)`

Below is the sorting logic (typescript playgroud - check console:

const main = [{"data":"x","numberField":1},{"data":"y","numberField":2},{"data":"x","numberField":3},{"data":"z","numberField":4},{"data":"q","numberField":5}]

// I'm using a Set instead of an array, because Set.has is faster than Array.includes
const fixedElements = new Set([3, 5])

main.sort((a, b) => {
  const aF = fixedElements.has(a.numberField)
  const bF = fixedElements.has(b.numberField)
  
  if(!aF && !bF) return b.numberField - a.numberField
  
  return +aF - +bF
})

console.log(main)

Answer №2

To sort the elements, you can implement a custom sorting function that checks for the existence of the value in the numberField within the fixedElements array. If it does exist, those elements will remain unsorted; otherwise, they will be sorted based on the numberField value.

let main = [{ data: 'x', numberField: 1}, { data: 'y', numberField: 2}, { data: 'x', numberField: 3}, { data:'z', numberField: 4}, { data: 'q', numberField: 5}], 
      fixedElements = [3, 5];
main.sort((a,b) => {
  if([a,b].some(({numberField}) => fixedElements.includes(numberField)))
   return +fixedElements.includes(a.numberField) - +fixedElements.includes(b.numberField);
  else
    return +b.numberField - +a.numberField
});
console.log(main);

Answer №3

To perform the check, utilize the includes() function within the context of the sort method.

var array = [{
    data: 'x',
    numberField: 1
  }, {
    data: 'y',
    numberField: 2
  }, {
    data: 'x',
    numberField: 3
  }, {
    data: 'z',
    numberField: 4
  }, {
    data: 'q',
    numberField: 5
  }],
  fixedElements = [3, 5];

array.sort((a, b) => {
  a = +a.numberField;
  b = +b.numberField;
  return (fixedElements.includes(a) - fixedElements.includes(b) || b - a);
});

console.log(array)

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

Utilizing vue-router to create two separate navigation bars where only one link is highlighted as active

In my setup, I have implemented two sections with navigation structured as follows: <ul class="navigation-list"> <li v-for="(route, index) in navRoutes"> <router-link :to="route.path"> <span>{{ route.name }}</span> ...

learning how to combine two json arrays of objects and showcase them in a react component

What is the best way to combine this data and present it in a table with a map using React? The text will be in the first column and the count in the second. const handleSubmit = async (event) => { event.preventDefault(); let URL1 = " ...

Issue with Three.js GLTF loader peculiar behavior while attempting to incorporate three-dimensional text

I had an idea to import a prebuilt gltf scene created in Blender, then add some 3D text using the ttf loader and manipulate it. Each loader worked perfectly when used separately, but strange things started happening when I combined them into a single scrip ...

Unveil the power of the "Enter" key with these jQuery hacks

Is there a way to prevent the Enter key from being counted as a character when disabling the submit button until something is entered in a TextArea? This functionality is achieved using the Count.js.coffee script. $(document).ready -> $(".cmnt_btn") ...

Ways to disable .animate() specifically for a particular element

I have implemented a countdown using which smoothly animates the numbers down and fades to opacity 0. Update. I have also created a demo on jsFiddle here: http://jsfiddle.net/Mw4j2/ // The .static class is added when the animation // complet ...

Pull JSON data from an Ajax application and cycle through the JSON values in a separate function

As I delve into the world of Ajax, I find myself grappling with a particular issue - the feasibility. My current endeavor involves fetching data from a db.json file using Ajax. { "transactions": [ { "date": "4/3/2021", "description": "Electric bill", ...

Using jQuery to verify the presence of an element, especially one that may have been dynamically inserted via AJAX

I have a good understanding of how to verify elements that are present when the document is loaded: jQuery.fn.exists = function () { return jQuery(this).length > 0; } However, this approach does not detect elements that are dynamically added via A ...

Using NodeJS and Express: redirection fails to load the specified endpoint

My current project involves a simple e-commerce web application running on localhost built with nodejs and express. Admins are required to register in order to gain access to functionalities such as adding, editing, and removing products from the product l ...

Exploring the Uses of SystemJS with TypeScript Loader

Can someone help clarify something about this TypeScript plugin for SystemJS? https://github.com/frankwallis/plugin-typescript/ Here is what the plugin does: This SystemJS plugin allows you to import TypeScript files directly and have them compiled in ...

Create dynamic modals in ReactJS that appear when a row is clicked

Engaged in a project for an undisclosed entity where patient data is retrieved from their API and displayed as modal on the page. Clicking on a modal reveals more threat information in another modal. The objective is for these modals to render based on a c ...

Issue encountered in Vuejs when attempting to remove a component using directives while the mounted or created event is still being executed

I created a custom directive that functions like v-if. In the directive, I check access rights and remove the element if access is not granted. Below is my code: Vue.directive('access', { inserted: function(el, binding, vnode){ // ...

Leveraging a returned value from a function in Typescript within a React component

I am currently facing a challenge where I need to extract values from a Typescript function and use them to dynamically render a React page. Specifically, the two values I am working with are the outputs of getIcon() and getSpaces(). This is how I attempt ...

Differentiating between mouseenter and tap events: What's the key?

When a mouseenter event is present, touch-enabled devices will activate this event when the user taps on the element. Is there a way to differentiate between an actual physical mouse entering and a simulated tap (which resembles a mouse enter)? ...

default choice in dropdown menus

I need to populate my option fields with data retrieved from a database. I encountered an error in the console: Error: [$compile:ctreq] Controller 'select', required by directive 'ngOptions', can't be found! I am confident that t ...

There seems to be an issue with the Link component from react-router-dom when used in conjunction with

I am currently utilizing react-router-dom along with Material-ui My main objective is to create a clickable row in a table that will lead to a specific path. Here is the code snippet: .map(client => ( <TableRow key={client.id} component={Link} to ...

Is it possible to convert JSON to enum using TypeScript?

I have a JSON string that looks like the following. { "type": "A", "desc": "AAA" } or { "type": "B", "desc" "BBB" } etc. How can I utilize an enum in Ty ...

The JQuery function .load() is not functioning correctly

How can I dynamically load a webpage's content into a div using JavaScript and jQuery? Here's what I have tried: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> When a s ...

Do not include any null or empty objects when assigning to an array in Mongoose

When using mongoose's find() or findOne() methods, the returned value will be [] and null, respectively, if the where conditions are not met. This can cause issues when assigning these values to an array. Currently, I am filtering out the null values ...

Create a receipt by utilizing jQuery with dynamically generated inputs

Is there a way to insert the descriptions and amounts of invoice items into the receipt, similar to the due date? The input for this section is dynamic with multiple rows that can be added or deleted. I'm considering using a counter that increments e ...

Working with Javascript objects and arrays

Need assistance with manipulating/updating a JavaScript array. Hoping for some help. The initial array looks like this: array('saved_designs'=array()); In Javascript JSON format: {"saved_design":{}} I plan on adding a label and its associa ...