What is the best way to arrange an array using AngularJs or Javascript?

When a user makes a selection, I want to sort and display an array in alphabetical order. Specifically, when we render data from the backend, I would like to display the fullName in alphabetical order. The $scope.selectedControlOwner is the ng-click event handler that triggers when a user selects owners from the modal window and clicks Ok. This will then trigger the ng-click event to display values on the parent window. At this point, I want to trigger the sorting function.

The

$scope.controlOwnerObj.workerName
is the ng-model that binds the values to the parent window.

Is there a solution using AngularJS or native JavaScript?

ctrl.js

$scope.selectedControlOwner = function() {
      $scope.controlOwnerObj.workerName= $scope.selectedOwners.map(function (owner) { return owner.fullName; }).join(';');
     };


    $scope.selectedOwners = [{
            "workerKey": 46958,
            "fullName": ,"Kumari, Swapna"
        }, {
            "workerKey": 746,
            "fullName": "Mike Piero",
        }, {
            "workerKey": 150918,
            "fullName": "A J, Jyothish",
        }],

Answer №1

utilize the sort feature found in JavaScript's array method

$scope.selectedOwners = [{
            "workerKey": 46958,
            "fullName": ,"Kumari, Swapna"
        }, {
            "workerKey": 746,
            "fullName": "Mike Piero",
        }, {
            "workerKey": 150918,
            "fullName": "A J, Jyothish",
        }],
$scope.selectedOwners.sort(function(a, b) {
  return a.fullName.localeCompare(b.fullName);
});

Answer №2

For the solution, I will be utilizing pure JavaScript as per your suggestion

The following code snippet sorts the numbers from lowest to highest:


var arr = [12, 213, 3, 121, 44, 12];
arr.sort(function (x, y) {
    return x > y;
})

It does not create a new array but sorts the existing one.

Result: [3, 12, 12, 44, 121, 213]

This code snippet sorts the numbers from highest to lowest:


arr.sort(function (x, y) {
    return x < y;
})

Result: [213, 121, 44, 12, 12, 3]

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

Tips on elevating a dragged div above all other elements when utilizing two scrollbars

Currently, I have two horizontal scrollers where I need to drag a div from the upper scroller to the lower scroller. While this functionality is working properly, there is an issue with the dragged div getting lost under the borders of the scroller during ...

Creating an Angular table row that can expand and collapse using ng-bootstrap components is a convenient and

I need assistance with an application I am developing, where I want to expand a table row to display details when it is clicked. The issue I am facing is that currently, all rows expand and show the data of the clicked row as seen in the image result below ...

Tips for concealing scrollbars across various browsers without compromising functionality

Is there a way to hide the scrollbar functionality on a horizontal scrollbar without using "overflow: hidden"? I need to maintain JS functionality and ensure compatibility with all modern browsers. $j = jQuery.noConflict(); var $panels = $j('#primar ...

``A fire tag is assigned depending on the existence of a div element

I have a task I need to complete on Wordpress blog pages, however there is no specific identifier in the URL. Instead, there are differences in content that can be used. Is there a method to trigger a tag (or event) based on the presence of a particular ...

Guide to changing an image on a canvas with KineticJS

I am currently working on developing a canvas that will display a hotel floor view. I have images stored in a database which I am drawing onto the canvas using x and y coordinates from the database as reference points. However, I want to add touch events t ...

Babelify is having trouble transpiling JSX code within the node_modules directory

I have successfully set up Babelify to transpile jsx code to js, and I've created node_modules before, allowing me to link them without a specific file path, just the package name. However, when I add jsx code within my node_module code, babelify flag ...

How to mock nested functions within sinon

There are several questions similar to this one, but none of them quite match the scenario I'm dealing with. The situation involves a function that takes another function as a parameter: var myfunc = (func_outer) => { return func_outer().func ...

Transforming Image Annotation from Angular 1 to Angular 4: Overcoming Conversion Challenges and Comparing Equivalents from 1.x to 4

After exploring various options, I am still struggling to resolve the conversion error that occurs when trying to convert my Angular 1.x script for image annotation into Angular 4. The equivalent of angular 1.x code in Angular 4 is not readily available. H ...

Manipulating Strings in JavaScript Arrays

I am working with an array of arrays of data that is being retrieved from a csv file. My goal is to filter out specific indexes of an array based on the titles they contain. For instance: If an array index includes the title "Retail", I want to return the ...

Preventing Cross-Site Scripting (XSS) when injecting data into a div

I am using Ajax to fetch data in JSON format and then parsing it into a template. Here is an example of the function: function noteTemplate(obj) { var date = obj.created_at.split(/[- :]/), dateTime = date[2] + '.' + date[1] + '. ...

Is it possible to modify the sub/child divs within a draggable parent div and assign them a different class?

Greetings, after being a long-time reader, I have finally decided to post for the first time. In the process of creating a webpage with jQuery drag and drop divs, I am curious about how to change the class of a child div within a draggable div once it is d ...

Obtain the JSON object by provided criteria

In the given JSON data, how can I access an object based on the provided applicationName? { "apps": [ { "applicationName": "myTestApp", "keys": [ { "key": "app-key", ...

Deselect a checkbox that is already selected and choose the current option in the multiselect dropdown

I've created a code that allows for single select in a multiselect dropdown, disabling other options once one is chosen. However, I don't want to disable the checkboxes and would like to uncheck the selected option if a new one is chosen, all whi ...

How can you transfer array elements to a new array using JavaScript?

I have a task to transform the fields of an array received from one server so that they can be understood by another server for upload. My approach involves first retrieving and displaying the original field names from the initial server's array to al ...

Utilizing Vue.js to display raw HTML content in elements.io table

I am trying to display HTML data in a table using Vue.js. new Vue({ el: "#app", data: { todos: [ { text: "<p>Learn JavaScript</p>", done: false }, { text: "<p>Learn Vue</p>", done: false ...

Exploring the usage of arrays within Angular 4 components. Identifying and addressing overlooked input

I'm struggling with array declaration and string interpolation in Angular 4 using TypeScript. When I define the following classes: export class MyArrayProperty { property1: string; property2: string; } export class MyComponent { @Input() object: ...

Choose a specific value from a drop-down menu

Looking for a solution with this piece of code: $('#Queue_QActionID').change(function () { if ($(this).val() == '501' || $(this).val() == '502' || $(this).val() == '503' || $(this).val() == '504' || $( ...

Error: Trying to assign a value to a null property

I am facing an issue while trying to dynamically create "iframe's textarea" and insert the value of a variable. Unfortunately, I keep encountering an error. Any suggestions on how to resolve this problem? P.S: Using Google Chrome as the browser ...

What is the best way to conceal a dynamically-loaded element on a webpage?

I wrote a script that utilizes AJAX to fetch data from a PHP file named names.php. Later in the script, I used jQuery's $(document.ready(function(){}); to attempt hiding a div when the DOM is loaded. Strangely, the $("div").hide() function isn' ...

Substitute this.bindMethod for function component

I have a class component that is structured like this: interface MyProps { addingCoord: any resetCoords: any } interface MyState { x: any y: any } class DrawerOld extends React.Component<MyProps, MyState> { width: number height: number ...