restructure array upon alteration of data

Here's the current structure of an array stored in a $scope variable:

$scope.objects: [
  {selected: true, description: 'string1'},
  {selected: false, description: 'string2'},
  {selected: true, description: 'string3'},
  {selected: true, description: 'string4'}
]

The "selected" property is controlled by checkboxes on the user interface.

I'm seeking a solution to monitor changes in the "selected" properties within the array. Whenever a change occurs, the array must be rearranged.

Objects with "selected:false" should be moved to the end of the array. The updated array would appear like this:

$scope.objects: [
  {selected: true, description: 'string1'},
  {selected: true, description: 'string3'},
  {selected: true, description: 'string4'},
  {selected: false, description: 'string2'}
]

If the selected value of the second element, for instance, is switched to false, the array should be reordered as follows:

$scope.objects: [
  {selected: true, description: 'string1'},      
  {selected: true, description: 'string4'},
  {selected: false, description: 'string3'},
  {selected: false, description: 'string2'}
]

I am in need of assistance with this task. Can anyone offer any help?

Best regards

Answer №1

To streamline your process, consider implementing a filter that handles the sorting task automatically.

One approach you could take is utilizing a library like lodash.
The code snippet provided below is just a rough draft and may need adjustments before being fully functional.

app.filter('customSort', function() {
    return function(items) {
        var groups = _.groupBy(items, 'selected');
        
        var selected = _.sortBy(groups[true], 'description');
        var unselected = _.sortBy(groups[false], 'description');

        return selected.concat(unselected);
    };
});

Answer №2

Success!

This solution was inspired by Pjetr's innovative idea.

Within the user interface (and the ng-repeat that iterates through the array):

<input type="checkbox" ng-change="orderUnselected()" ng-model="object.selected">

in the controller:

$scope.orderUnselected = function() {
    var selectedItems = [];
    var unselectedItems = [];

    for(var index = 0; index < $scope.objects.length; index++) {
        var currentObject = $scope.objects[index];
        if(currentObject.selected == true) {
            selectedItems.push(currentObject);
        } else {
            unselectedItems.push(currentObject);
        }
    }

    $scope.objects = selectedItems.concat(unselectedItems);
}

This approach is effective and does not result in any scope-related issues.

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

Determine the data type of a string without needing to convert it

Can you determine if a value is numeric without casting it? For example, how can you differentiate between 'abc' and '123' without converting them to a specific data type? While visually apparent that 'abc' is not numeric, t ...

The jQuery fadeToggle function toggles the visibility of an element starting from hidden instead

I'm having an issue where text in my div only appears on the second click, instead of the first. What could be causing this problem? $('#fPaperCirclePic').on('click', function () { $('#fPaperCircleText, #isargebla, #moq10 ...

Exploring the World of C Pointers and Arrays

Can someone please explain the meaning of this code snippet in C? MDMA_Sobel_In_Des.StartAddress = (void *) (&Sobel_In_Buf0[0]); I am particularly curious about the right-hand side statement. Why is the address of the variable not directly assig ...

Exploring the process of passing an array as a function argument from PHP to JavaScript

I am looking for assistance in passing an array as a function argument from PHP to JS. The values I need are retrieved from a database. while ($rows = pg_fetch_array($qry)) { ?> <option value="<?php echo $rows[&ap ...

Is there a way to obtain HTML code within a contentEditable DIV?

When working in a contentEditable-DIV, my goal is to extract the HTML code from the starting position (0) to the end position where the user has clicked. <div id="MyEditableId" contentEditable="true"> 1. Some text 123. <span style="background-c ...

Creating React components through the use of the map function

Utilizing the hackernews api, I am attempting to extract the "data" property from my response object in order to display each story title individually on the browser. Initially, the data is structured as an array of id's representing individual storie ...

The Authorization Header is added just once during an AJAX CORS request

I am making calls to my RESTful API from JavaScript in a CORS scenario. To send my POST authenticated request, I am utilizing JQuery. Below is an example: function postCall(requestSettings, includeAccessToken) { requestSettings.type = 'POST& ...

The issue of CSS not being applied to HTML content after being inserted via AJAX has been encountered

I've successfully implemented AJAX to retrieve specific page content from a database, but now I'm facing an issue: When it comes to the 'Contact' page, the form retrieved from the database (as HTML) is not applying the CSS styles I hav ...

Ways to retrieve and update the state of a reactjs component

I'm facing an issue with modifying a React JS component attribute using an event handler. export default interface WordInputProps { onWordChange:(word:string) => void firstLetter:string disabled?:boolean } These are the props for my co ...

Trouble with ng-model when attempting to validate password confirmation using $setValidity()

I've been working on implementing a "confirm password" feature in an Angular form <input type="password" name="password" ng-model="regFormData.password" ng-change="dupCheck(regForm.password,regForm.repassword)" required=""/> <input ...

Anyone have a sample showcasing the integration of VueJS with the latest webpack 4 configuration?

VueJs templates now come with numerous examples and starting project skeletons. However, most of them still utilize webpack v3. Has anyone experimented with webpack 4? I'd love to see how you integrate version 4 of webpack into a VueJs project. Thank ...

Vercel deployment issue: Hidden input values not being detected as expected

Whenever I attempt to update the data on Vercel, an error message is displayed: invalid input syntax for type uuid: "undefined" - unable to save Oddly enough, the data updates successfully when done locally. This is how I submit the form: <form onSu ...

What steps can be taken to avoid special characters in ion-input fields?

When inputting special characters into the field used for storing the alphanumeric serial number, they are accepted. I need to prevent special characters from being entered in the input field. <ion-input [(ngModel)]="serial_number" (ngModelCha ...

Height of the Accordion List

I have a code snippet below for an accordion list that I put together. I initially set the height for all the heading boxes to be uniform, but it seems like box A is displaying larger than the others. Can you help me figure out what went wrong? Any suggest ...

Update the scrollspy navigation in a div with overflow by toggling the active class

Struggling to implement a navigation menu within a self-scrolling div using html/css/jquery. Looking for the menu items to toggle the active class when in view or at the top of the scrolling div. I'm essentially trying to achieve something like this ...

Challenge with inserting documents in Mongoose database

I have set up a schema and now I am trying to insert data into a MongoDB collection, but I keep getting an error stating that diagramModel.insert is not defined. Can anyone help me figure out what I did wrong? app.js mongoose.connect('mongodb://lo ...

AngularJS, Implement a "read more" feature after a specified number of characters

Is there a way to implement a "read more" tag in Angular that will automatically appear if a string exceeds 100 characters? I've been searching for an example without any success. Any help would be appreciated. Edit: -- SUCCESS! Thanks to Don' ...

Create a copy of a div element once the value of a select element has

After modifying a select option, I'm attempting to replicate a div similar to the example shown in this link: http://jsfiddle.net/ranell/mN6nm/5/ However, instead of my expected lists, I am seeing [object]. Any suggestions on how to resolve this issue ...

Having trouble with the Vuejs validation code not functioning correctly?

I need help with a JavaScript function that posts objects to the backend only if all items are numbers. Here is the code snippet I'm working with: var MyApp = new Vue({ el: '#my_element', data: { errors: [], ...

My AngularJS app is refusing to launch when using the npm start command

Yesterday, I was working through the AngularJS tutorial for angular-phonecat on my MacBook and everything was running smoothly. However, both npm start and npm test required sudo to function properly, which seemed odd. Today, I decided to clone the origin ...