Sorts a JavaScript object array by the specified attribute and sort direction

Source: Internet
Author: User
Tags sorts java web

Introduction

In a data-centric information system, presenting data in tabular form is a common approach. Sorting the data is an essential feature. Sorting can be sorted by individual fields and sorted by multiple fields in different sort directions. Single-field sorting is more limited, it can't meet the demand of the user to change the attention point of the data, and the multi-fields sorting can make up the flaw better.

Multi-field sorting, the way of implementation from a large level can be divided into backend implementation and front-end implementation.

Back-end sorting

Back-end implementation sequencing can be implemented at the database level or at the application level.

The database level implementation of multi-field ordering is very simple, using the SQL sort instruction " Order By " can-- Order By field1 asc, field2 desc, field3 asc -- ... .

The application level refers to the Web application layer (the C/s architecture is not discussed here), such as PHP, Java Web, ASP. NET, and so on. Application-level implementations are using PHP, Java, and. NET (C#/VB) These back-end service languages to enable sorting of data. In the case of ASP. C #, because LINQ has built up many operations on collection types and supports multi-attribute sorting, it is easy to do so with LINQ- from f in foos orderby f.Name descending, f.Num ascending select f (You can see that LINQ's sort syntax is almost identical to SQL). If other languages do not have similar support built into them, they are implemented according to the sorting algorithm, which is generic and irrelevant to the programming language.

Front-end sequencing

In JavaScript, the array has an ordering method of "sort", which can be conveniently reached when the array is a simple array (array elements are simple types-string, numeric, and Boolean). But when an array element is a non-simple type, such as an object of a name/value pair, and you want to sort by a different sort direction for a specified number of properties, simply calling the "sort" method does not do this.

Fortunately, the "sort" method allows you to sort the order by reserving the interface for custom sorting.

Let's look at how the array's "sort" method is.

Sort function Prototypes
The elements of an array are sorted in situ, and the array is returned.//by default is sorted by the Unicode code point of the string. array.prototype.sort ([Comparefunction]:number); //number:-1 | 0 | 1. //a typical comparison function (ascending sort). function compareFunction (item1, item2) {if (Item1 > item2) {1; //if it is in descending order, return-1. }else if (item1 = = = item2) {return 0;} else {return-1; //returns 1 if it is in descending order. }} 

Note: If comparefunction is not specified, the elements are converted to characters of the string and sorted by the Unicode bit order. For example, "Cherry" will be lined up before "banana". When numbers are sorted, 9 appears before 80 because they are converted to strings first, and "80" is higher than "9".

    • If Comparefunction (A, b) is less than 0, then A is arranged before B;

    • If Comparefunction (A, B) equals 0, A and b
      The relative position of the same. Note: The ECMAScript standard does not guarantee this behavior, and not all browsers will adhere to it (e.g. Mozilla in 2003

Years prior to the release);

    • If Comparefunction (A, b) is greater than 0, B is arranged before a.

    • Comparefunction (A, B) must always return the same comparison result for the same input, otherwise the result of the sort will be indeterminate.

Note: The sorting results from the above rule are ascending, if you want to get the result in descending order, the result of less than 0 is returned when the comparison result is greater than 0 o'clock, and the result is less than 0 o'clock to return more than 0 results.

To realize multi-attribute ordering, the key is to implement the comparison function. According to the above rules, the multi-attribute is sorted in different directions, and the size relationship of the two comparison items is still returned. So how do you determine the size relationship of multiple Property objects? This can go in two steps.

The first step is to record the results of the two sort items that are compared according to the respective sorting properties and orientations.

var proporders = {"Prop1":"ASC","PROP2":"Desc","PROP3":"ASC"};functionCmp(Item1, item2, Proporders) {var cps = [];Compare results for recording individual sorting properties, 1 | 0 | 1.var ISASC =true; //sort direction. for (var p in propOrders) {ISASC = Proporders[p] = = =  "ASC"; if (Item1[p] > Item2[p]) {Cps.push (isasc?) 1:-1); break; //can jump out of the loop, because there is already known item1 "greater than" item2. } else if (item1[p] = = = Item2[p]) {Cps.push (0); } else {cps.push (isasc?-1: 1); Span class= "Hljs-keyword" >break; //can jump out of the loop, item1 "less than" item2. }} /* ... */}            

In the second step, the final size relationship of the two comparison items is obtained synthetically according to the comparison results of each sort attribute.

    /*      .     .     .     */        for(var j = 0; j < cps.length; j++) {        if(cps[j] === 1 || cps[j] === -1) { return cps[j]; } } return 0;

With these ideas in mind, it is easy to implement the entire comparison function, the following is the complete JavaScript code for the comparison function:

comparison function
functionSortbyprops(Item1, ITEM2) {"Use strict";var props = [];for (var _i =2; _i <Arguments.length; _i++) {props[_i-2] =Arguments[_i]; }var cps = [];Stores the sorting property comparison result.If no sort attribute is specified, the full attribute is sorted in ascending order.var ASC =Trueif (Props.length <1) {for (var pIn item1) {if (Item1[p] > Item2[p]) {Cps.push (1);Breakis greater than when the loop jumps out. }Elseif (item1[p] = = = Item2[p]) {Cps.push (0); }else {Cps.push (-1);Breakis smaller than the loop. } } }else {for (var i =0; i < props.length; i++) {var prop = Props[i];for (var oIn prop) {ASC = Prop[o] = = ="ASC";if (Item1[o] > Item2[o]) {Cps.push (ASC?1:-1); Break ; //greater than when jumping out of the loop. } Else if (item1[o] = = = Item2[o]) {Cps.push (0);} else {cps.push (ASC-1: 1); Break ; //Less than when jumping out of the loop. }}}} for (var j = 0; j < Cps.length; J + +) { if (cps[j] = = 1 | | cps[j] = = =1) {  return CPS[J]; }} return 0;}                 
Test Cases
    -------------Test Case------------------------------var items = [{name:' Edward ', value:}, {name:' Sharpe ', value:PNS}, {name:' and ', Value:}, {name:' Edward ', Value:-}, {name:' Magnetic ', value:}, {name:' Zeros ', value:37}];functionTest(proporders) {Items.Sort (function(A, B) {Return Sortbyprops (A, B, proporders); });Console.log (items); }functionTestasc() {Test ({"Name":"ASC","Value":"ASC"}); }function Testdesc() {test ({ "name": "desc", "value": "desc"}); function Testascdesc() {test ({ "name": "ASC", "value": "desc"}); function testdescasc() {test ({ "name": "desc", "value": "ASC"});   
Typescript Code
/**** the sort direction. */type Direct ="ASC" |"Desc";/**** the Sort property. * * * * @interface ipropertyorder*/interface Ipropertyorder {[name:string]: Direct;}/**** a simple name/value object. * * * * @interface isimpleobject*/interface isimpleobject {[name:string]: string | number | Boolean;}/**** sorts a simple name/value object by the specified attribute and sort direction (depending on the sort attribute and sort direction, * * Compares two items sequentially and returns the value representing the sort position). * * * @template T Simple name/value object. * * @param {T} item1 sort comparison item 1. * * @param {T} item2 sort comparison item 2. * * @param {... Ipropertyorder[]} Props Sort property. * * @returns If Item 1 is greater than Item 2 returns 1, if Item 1 equals item 2 returns 0, otherwise returns-1. */functionsortbyprops<TExtendsIsimpleobject>(Item1:t, Item2:t, ... props:ipropertyorder[]) {"Use strict";var cps:array<number> = [];Stores the sorting property comparison result.If no sort attribute is specified, the full attribute is sorted in ascending order.var ASC =Trueif (Props.length <1) {for (var pIn item1) {if (Item1[p] > Item2[p]) {Cps.push (1);Breakis greater than when the loop jumps out. }Elseif (item1[p] = = = Item2[p]) {Cps.push (0); }else {Cps.push (-1);Breakis smaller than the loop. } } }else {Sort by the specified attributes and ascending and descending direction.for (var i =0; i < props.length; i++) {var prop = Props[i];for (var oIn prop) {ASC = Prop[o] = = ="ASC";if (Item1[o] > Item2[o]) {Cps.push (ASC?1:-1); Break ; //greater than when jumping out of the loop. } Else if (item1[o] = = = Item2[o]) {Cps.push (0);} else {cps.push (ASC-1: 1); Break ; //Less than when jumping out of the loop. }}}} for (var j = 0; j < Cps.length; J + +) { if (cps[j] = = 1 | | cps[j] = = =1) {  return CPS[J]; }} return 0;}                 
Usage scenarios and limitations

Using JavaScript at the front end enables multi-attribute sorting, reducing server-side requests and computing pressure on the server, but only for situations where local data needs to be sorted. If you need to sort the entire dataset with multiple attributes, you will end up at the server-side database level.

Sorts a JavaScript object array by the specified attribute and sort direction

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.