Arrange several columns according to the chosen criteria

There is a dropdown feature in my application that has three states - ascending, descending, and none. This dropdown is responsible for rearranging the items in a list.

https://i.sstatic.net/xYIfM.png

This is my code:

list.component.html

<div *ngFor="let item of items; index as i">
  <ui-list-item
      [body]=getItem(item)"
  ></ui-list-item>
</div>

list.component.ts

getItem(item){
     const toggle = {Price: true, Active: false, Modifiers: true}
     let list = [
         {label:"Price", value:item.price}, // e.g. "$10.00"
         {label:"Active", value:item.active}, // e.g. true
         {label:"Position", value:item.position} // e.g. 1
         {label:"Category", value:item.category} // e.g. "Food"
     ];
     return list;
}

When the toggle value is true, the items are sorted in ascending order. If the toggle value is false, then the order is descending.

I am looking to implement a sort function based on the toggle values from left to right. Additionally, as the labels contain various value types, I need to detect the type and arrange the items accordingly.

I came across this helpful resource How to sort an array of objects with labels according to other array of labels?, but it doesn't seem to be solving my issue.

Here is my updated answer (still not working):

getItem(item){
 const toggle = {Price: true, Active: false, Modifiers: true}
 let list = [
     {label:"Price", value:item.price}, // e.g. "$10.00"
     {label:"Active", value:item.active}, // e.g. true
     {label:"Position", value:item.position} // e.g. 1
     {label:"Category", value:item.category} // e.g. "Food"
 ];

list = list.sort((a: any, b: any) => {
      if (typeof toggle[a.label] === 'boolean') {
        if (toggle[a.label]) return a.value - b.value;
        else return b.value - a.value; 
      } else {
        return 0;
      }
 });

 return list;

}

Could the issue be that I am not fetching the entire list to perform the sort function? Thank you for your assistance!

Answer №1

let sortedList = list.sort((firstItem:any, secondItem:any) => {
    if(firstItem.title !== secondItem.title){ // checking if titles are not the same
        return firstItem.title.localeCompare(secondItem.title) 
    }
    if(typeof toggle[firstItem.title] == 'boolean'){
      if(toggle[firstItem.title])
        return firstItem.value.localeCompare(secondItem.value)
      else
        return secondItem.value.localeCompare(firstItem.value)
    } else {
      return 0
    }
    }

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

Is Angular considered bad practice due to its reliance on singletons, despite its widespread use and popularity?

Angular relies on singletons for all its services, however using singletons is often frowned upon in the development community. Despite this controversy, I personally find Angular to be a valuable and effective tool. What am I overlooking? ...

How can I maintain focus selection while replacing HTML with text in a contenteditable div without losing it?

When working with a div tag that needs to be editable, the goal is to prevent users from entering any HTML into the tag. However, despite efforts to restrict input, when users copy and paste content, it often includes unwanted tags. To address this issue, ...

Unidentified file: Error reading property 'filename'

I have a function that retrieves the file name. The file name is displayed in an input field, but the background color of the input field is only visible when a file is selected and the file name is populated there. I would like the background color to b ...

In a C program, when a value is subscripted, it is not an array, pointer, or

My program receives an img_ptr of size 448x448, which is divided into 4 equal parts. Each corner of the image undergoes filtering, and now I am attempting to reconstruct the image using the 4 parts stored in subBlockList[]; I encountered the following err ...

Show occurrences of elements in an array as "Number x repeats x times"

Is there a way to modify my code to display only one number with the duplicate count from an array? I attempted to use the traditional method, but the output shows duplicates on multiple lines, such as "2 repeats 2 times" repeated for each instance, when ...

Assortment of elements with varying range and functionalities

Is there a way to develop a software that generates an array filled with random integers, where the user can specify the number of integers and the range of the generated numbers? Additionally, could this program then offer a menu for the user to perform ...

Could there be a mistake in the way array combinatorics are implemented in JavaScript?

Having encountered the necessity for generating unique combinations when dealing with multiple arrays, I developed this script. While it functions as intended during the combination process, storing the result in a final array yields unexpected outcomes. ...

scrolling through a list using .slice choosing an excessive amount of items

Is it possible to create a dynamic pager that can be customized using parameters from the URL? I have noticed that when I hardcode the perTime variable, everything works fine. However, as soon as I try to use a parameter from the URL, the page starts behav ...

Phonegap app: The function in the AngularJS controller is only executed when called twice

I am currently developing a phonegap app using angularJS, and I have encountered an issue with a function in one of my controllers. Here is how my controller looks like: function NavCtrl($scope,navSvc) { $scope.slidePage = function (path,type) { ...

Move buttons from one group to another group

I have a task to update a group of buttons with different buttons depending on the initial button chosen. Button1: when clicked, both buttons will be replaced by Button1a and Button1b Button2: when clicked, both buttons will be replaced by Button2a ...

Triggering an automatic pop-up window using JavaScript based on a PHP condition

I have developed a hidden pop-up box that becomes visible when targeted, with its opacity increasing to one. I am aiming for the pop-up to appear if the user is identified as a "firstTimeUser," a status saved in a PHP $_SESSION variable. However, I am stru ...

Bringing PlayCanvas WebGL framework into a React environment

I am currently working on integrating the PlayCanvas webGL engine into React. PlayCanvas Github Since PlayCanvas operates on JS and the code remains in my index.html file, I am facing challenges in comprehending how it will interact with my React compone ...

What benefits does registering a Vue component locally provide?

According to the Vue documentation, global registration may not always be the best option. The documentation states: Global registration is not always ideal. When using a build system like Webpack, globally registering all components can result in unnece ...

"Create dynamic tables with AngularJS using ng-repeat for column-specific rendering

I have a model called Item with the following structure: {data: String, schedule: DateTime, category: String} I want to create a report that displays the data in a table format like this: <table> <tr> <th>Time Range</th&g ...

Is it possible to use multiple schemas for one collection name?

I am currently working on creating different schemas for a single collection, such as User or subUser. I aim to store both User and subuser data in the same collection but with different schemas. Here is an example of my schema file: export const AryaSchem ...

I am encountering an issue where the threejs lighting effects, such as pointlight and ambientlight, are not functioning properly in version "three": "^0.164.1". What could be causing this problem

Embarking on my first threejs project using vite and the threejs library I implemented the following light functions in my JS file: // Emit light evenly in all directions from a specific point in space const pointLight = new Three.PointLight(0xff0000, 1, ...

Angular directive compatibility with Mozilla Firefox

I've encountered a strange issue with my directive in Firefox. The directive is designed to limit user input, and it functions correctly in Chrome. However, in Firefox, once the user reaches the input limit, they are unable to delete any characters - ...

Retrieve data using the designated key and convert it into JSON format

If I have the following JSON array: [ {"data": [ {"W":1,"A1":"123"}, {"W":1,"A1":"456"}, {"W":2,"A1":"4578"}, {"W":2,"A1":"2423"}, {"W":2,"A1":"2432"}, {"W":2,"A1":"24324" ...

The browser has surpassed the maximum call stack size while trying to refresh with socket.io, causing an error

I've encountered an issue with my Node js server crashing whenever I refresh the browser. The websocket connection works fine initially, but upon refreshing, the server crashes with the following error: E:\Back\node_modules\socket.io-pa ...

Experience the classic game of rock-paper-scissors brought to life through JavaScript and HTML,

I've been working on a rock, paper, scissors game in JavaScript and I'm struggling to get the wins and losses to register correctly. The game keeps resulting in a draw even though I've checked my code multiple times. It's frustrating be ...