Can someone explain to me how this ternary operator works?

Can anyone demonstrate how to convert this function into a traditional if-else statement?

export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => ((a[key] > b[key]) ? 1 : (a[key] === b[key]) ? ((a[key] > b[key]) ? 1 : -1) : -1));

I need to incorporate an additional condition, but the current structure is making it difficult for me to understand.

Answer №1

To start, let's modify the code to improve its readability.

It is worth noting that the ?: part seems to have some questionable logic, as it uses === for comparison but then switches to non-strict comparisons like < and >. For the sake of clarity in this response, let's assume it is not meant for sorting arrays with mixed types or, if it is, it will disregard strict type checks (i.e., === should be replaced by ==)

function orderArr (arr: any[], key: string) {
  function sorter(a, b) {
    return (
      (a[key] > b[key]) 
      ? 1 
      : (a[key] === b[key]) 
        ? (
          (a[key] > b[key]) 
            ? 1 
            : -1
        ) 
        : -1
    );
  }
  return arr.sort(sorter);
}

export orderArr;

Let's now simplify the complex ?: expression (complex not due to ?: syntax but because it is overcomplicating things unnecessarily) by converting it to if-else statements (please note, this code is still incorrect)

function sorter(a, b) {
   if (a[key] > b[key]) {
     return 1;         // return 1 if a > b 
   } else {
     if (a[key] === b[key]) {        // questionable logic
       if (a[key] > b[key]) {        // questionable logic
         return 1;
       } else {
         return -1;      // will always return -1 (wrong, a == b should return 0)
       }
     } else {
       return -1;     // return -1 if a < b
         // or if type of a does not equal type of b (questionable)
     }
   }
}

We can further simplify and correct the bug (by removing the strict type comparison). This can be achieved using early return technique (guard clauses) and avoiding unnecessary indentation caused by excessive use of else statements

function sorter(a, b) {
   if (a[key] > b[key]) return 1;
   if (a[key] < b[key]) return -1;
   return 0;
}

Alternatively, utilizing the ?: syntax

function sorter(a, b) {
   return a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0;
}

If you are dealing with numeric values, you can employ a simple trick to further streamline the code. As per the requirements of sort function – returning 0 for equal elements, negative for a < b, and positive for a > b - we can simplify numeric sorting as follows:

function sorter(a, b) {
   return a[key] - b[key];
}

Now, let's consolidate all the simplified code into a single line. Firstly, for arrays of any data type.

export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0);

And for numerical arrays specifically

export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => a[key] - b[key]);

Answer №2

export const orderArr = (arr: any[], key: string) => {
    return arr.sort((a, b) => {
        if (a[key] > b[key]) {
            return 1;
        } else if (a[key] === b[key]) {
            if (a[key] > b[key]) {
                return 1;
            } else {
                return -1;
            }
        } else {
            return -1;
        }
    })
}

In my opinion, using nested ternary operators with multiple levels can greatly decrease code readability without adding significant benefits.

For better clarity, I recommend rewriting the method using simple if/else or switch statements.

Answer №3

Yes, you are right. It's not recommended to nest ternary operators as it can make the code difficult to read and understand.

In your situation, consider the type of data you are working with. For numeric values, you can use a[key] - b[key]. If dealing with strings, consider using a[key].localeCompare(b[key])

Answer №4

Here is the if else version of the code without considering any logical implications:

const sortArray = (arr, key) => {
  return (
    arr.sort( (a,b) => {
      if(a[key] > b[key]) {
        return 1
    }
    else if(a[key] === b[key]) {
        if (a[key] > b[key])
        return 1
        else return -1
    } else {
      return -1
    }
    })
  )
}

Answer №5

If-y version

const iffyOrderArray =
  (arr: any[], key: string) => arr
    .sort((a, b) => {
      if (a[key] > b[key]) {
        return 1;
      } else {
        if (a[key] === b[key]) {
          if (a[key] > b[key]) {
            return 1;
          } else {
            return -1;
          }
        } else {
          return -1;
        }
      }
    });

Original Version(Formatted)

const orderArr =
  (arr: any[], key: string) => arr
    .sort((a, b) =>
    ((a[key] > b[key])
      ? 1
      : (a[key] === b[key])
        ? ((a[key] > b[key])
          ? 1
          : -1)
        : -1));

const orderArr = (arr, key) => arr
  .sort((a, b) => ((a[key] > b[key]) ?
    1 :
    (a[key] === b[key]) ?
    ((a[key] > b[key]) ?
      1 :
      -1) :
    -1));

const iffyOrderArray = (arr, key) => arr
  .sort((a, b) => {
    if (a[key] > b[key]) {
      return 1;
    } else {
      if (a[key] === b[key]) {
        if (a[key] > b[key]) {
          return 1;
        } else {
          return -1;
        }
      } else {
        return -1;
      }
    }
  });

const testArray = [{
  a: 42
}, {
  a: 21
}, {
  a: 23
}, {
  a: -45
}];

const testKey = "a";

console.log("Original", orderArr(testArray, testKey));

console.log("Revised", iffyOrderArray(testArray, testKey));



When it comes to Stackoverflow, WYSIWYG means WHAT YOU SHOW IS WHAT YOU GET

Answer №6

Update:

After considering @Erich Kitzmueller's advice, I have made a modification to the code by removing a[key] === b[key] section:

export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => 
{
    if(a[key] > b[key]){
        return 1;
    } else {
        return -1;
    }
}
);

Original Post:

While unsure about the structure of the sort function, here is how the if statement was initially written:

export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => 
{
    if(a[key] > b[key] || a[key] === b[key]){
        return 1;
    } else {
        return -1;
    }
}
);

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

Passing props to a wrapped component when utilizing a higher order component in React

While exploring the react documentation, I came across a section on Higher-Order Components that included an example of logging props for a specific component. function logProps(WrappedComponent) { return class extends React.Component { componentWillR ...

What are the best practices for integrating Firebase authentication pre-made UI in Next JS?

As someone new to React and NextJS, I am eager to implement an authentication service for my NextJS web application in order to manage user accounts efficiently. I am particularly interested in utilizing a familiar user login solution that offers a compre ...

At all times, AJAX/PHP/JS will have a readyState of 1 and a Status of 0, with no text response

Recently, I've been attempting to utilize a sample of AJAX to compare form data with an SQL database from a domain at http://www.example.com. However, I'm encountering persistent issues where the readyState remains at 1 and the Status is always 0 ...

A comparison of copyFileSync and writeFileSync

I've been working on file manipulations and I came across this interesting dilemma. I tried searching online for a solution but I couldn't find a good, precise answer. Which method do you think is more efficient for copying a file? readFileSync ...

How can I open a new window, redirect the current one, and bring focus to the new window using JavaScript?

Trying to troubleshoot a problem I'm having with the following setup: - Using SAP Portal, I am launching an HTML page containing this code. - The goal is for the HTML page to open a new window. - Once the new window opens, the original HTML page ...

Iterate through a collection of objects, check their unique identifiers, and combine the objects together based on their

I am currently iterating through an array of objects in an attempt to extract the id and carId values from them. My code snippet looks like this: getIds(array) { for (var index in array) { var combinedIds = array[index]; if ...

Strategies for integrating a username-only login using Firebase without requiring a password or email address

For my class assignment, I'm developing a webapp and want to implement a login system with only a username. However, when I try sending just the username to the database, it gets stored as a child under the connection ID in Firebase. Below is the Java ...

Navigating an Angular JSON object: A guide

I have successfully created a nodejs application that reads all the databases in my mongo Db when I run it in the console. However, I am facing an issue when trying to parse the data into a json object and display it on the screen. If anyone can guide me o ...

Showing an array in an ASPX page using C# codebehind

Having a string array of survey responses called "answers" poses a challenge. For example, the answers array is defined as follows: string[] answers = new string[10] {"Y", "Y", "N", "Y", "N", "Y", "N", "Y", "N", "Y"}; In order to display each individua ...

Can one manipulate SVG programmatically?

Looking to develop a unique conveyor belt animation that shifts items on the conveyer as you scroll down, then reverses when scrolling up. I discovered an example that's close to what I need, but instead of moving automatically, it should be triggered ...

Increase or decrease the quantity of items by cloning with Jquery and dynamically changing the ID

Currently, I am working on a jQuery clone project where I need to dynamically add and delete rows. Despite searching extensively on Stack Overflow and Google, I only have a basic understanding of how jQuery clone works. Any suggestions would be greatly ap ...

Incorporate a new method into a TypeScript class from a separate file

I'm curious about the feasibility of adding additional functions to a class prototype in Typescript. Here's my dilemma: I have a file containing a class, for example image.ts: export class Image { b64img: string; } Since this class is gene ...

Error: The property 'slice' cannot be read from an undefined value

I am currently working on a prototype recipe app called Forkify, which is being developed using Javascript, NPM, Babel, and Webpack. In this project, I am utilizing a custom API. API URL : forkify-api.herokuapp.com TO SEARCH RESULT This API returns a l ...

Tips for managing the data type of a bound value through ngModel: preventing number distortion to string

I posted a query and managed to solve it. However, I observed that even though the provided data consists of objects defined like this: export interface GisPoint { e: number; n: number; } when a user inputs a value, the original content changes from { e: ...

Confirming changes to checkbox values in Angular 2 prior to updating

My current challenge involves implementing a confirmation dialog in my application, and I'm feeling a bit unsure about the logic behind it. UserDetailsComponent.ts import { Component, OnInit, OnDestroy, ViewChild, Input, OnChanges, SimpleChange } f ...

Discovering the byte information using pyserial readline in Python 3.x

Is there a way to locate the substring in serial byte data that is newline terminated? I simply need to extract the information from the UART stream. I'm struggling to locate byte data using Pyserial commands. Although I can successfully retrieve th ...

Does adding .catch resolve a promise?

Being new to typescript / javascript, I have limited knowledge about promises. My current scenario involves creating three distinct promises within a cloud-function and subsequently returning them using Promise.all([promise1, promise2, promise3]). Each of ...

Guide to incorporating a variable into the hyperlink function with Google Apps Script

Currently, I am utilizing Google Apps Script to create customized reports within Google Sheets. Within my spreadsheet, there is a column consisting of numbers that I would like to transform into hyperlinks. The URL for each hyperlink is mostly the same, wi ...

How can I ensure that the size of the Dropdown Menu Item matches its parent in both Bootstrap and CSS styles?

I am working on a navigation bar that has a dropdown menu which appears on hover. I want the size of the dropdown menu items to match the size of the parent element. Here is an image for reference: https://i.stack.imgur.com/oNGmZ.png Currently, the "One ...

Utilize the power of generics with Angular's service providers

Is it possible to make the membervar of class Parent generic instead of type any, while still retaining the ability to switch provider classes without having to update all components that rely on class Parent? For example, if class ChildB implements a diff ...