How to sort JavaScript Object arrays by specified attributes and sorting directions? javascript Array

Source: Internet
Author: User

How to sort JavaScript Object arrays by specified attributes and sorting directions? javascript Array

Introduction

In a data-centric Information System, it is common to present data in the form of tables. Sorting data is essential. Sorting can be divided into sorting by a single field and sorting by multiple fields in different sorting directions. Single-field sorting has many limitations and cannot meet users' requirements for changing data concerns. Multi-field sorting can make up for this defect.

Multi-field sorting can be divided into backend implementation and front-end implementation.

Backend sorting

Backend sorting can be achieved at the database level or at the application level.

Multi-field sorting at the database level is very simple. You can use the SQL sorting command "Order By" -- Order By field1 asc, field2 desc, field3 asc --....
The application layer refers to the Web application layer (the C/S architecture is not discussed here), such as PHP, Java Web, and ASP. NET. At the application layer, the backend Service languages PHP, Java, and. NET (C #/VB) are used to sort data. Use ASP. net c # is used as an example, because the LINQ in C # has many built-in operations on the set type and supports multi-attribute sorting, therefore, using LINQ can easily achieve this goal -- from f in foos orderby f. name descending, f. num ascending select f (it can be found that the sorting Syntax of LINQ is almost the same as that of SQL ). If other languages do not have similar built-in support, the sorting algorithm is used. This is common and has nothing to do with programming languages.

Frontend sorting

In JavaScript, an array has a sorting method "sort". When an array is a simple array (the array element is a simple type-string, value, and Boolean, this method can be used to conveniently sort objects. However, when an array element is of a non-simple type, such as an Object with a name/value pair, and you want to sort the elements in different sorting directions based on specified attributes, simply calling the "sort" method cannot achieve this goal.

Fortunately, the "sort" method reserves an interface for custom sorting to implement the desired sorting method.

Let's take a look at the "sort" method of the array.

Sort function prototype

// Sort the elements of the array in the original position and return the array. // By default, the string is sorted by the Unicode code point. Array. prototype. sort ([compareFunction]: number); // number:-1 | 0 | 1. // Typical comparison function (sort in ascending order ). Function compareFunction (item1, item2) {if (item1> item2) {return 1; // in descending order, return-1 .} Else if (item1 = item2) {return 0;} else {return-1; // if it is in descending order, return 1 .}}

NOTE: If compareFunction is not specified, the elements are converted to various characters of the string and sorted in the order of Unicode points. For example, "Cherry" is arranged before "banana. When the numbers are sorted, 9 will appear before 80, because they will be converted to strings first, and "80" is higher than "9.

• If compareFunction (a, B) is smaller than 0, a is arranged before B;

• If compareFunction (a, B) is equal to 0, a, and B

. Note: The ECMAScript standard does not guarantee this line, and not all browsers will comply with this line (for example, Mozilla in 2003
Versions earlier than the year );

• If compareFunction (a, B) is greater than 0, B is arranged before.

• CompareFunction (a, B) must always return the same comparison results for the same input; otherwise, the sorting results will be uncertain.

Note: The sorting results obtained by the above rules are in ascending order. If you want to get the results in descending order, a result smaller than 0 is returned when the comparison result is greater than 0, if the comparison result is smaller than 0, a result greater than 0 is returned.

To sort multiple attributes, the key lies in the implementation of comparison functions. Based on the above rules, to achieve multi-attribute sorting in different directions, we still need to return the size relationship between two comparison items.

How can we determine the relationship between the sizes of Multiple Attribute objects? This can be done in two steps.

The first step is to record the comparison results of the two sorting items based on each sorting attribute and direction.

Var propOrders = {"prop1": "asc", "prop2": "desc", "prop3": "asc"}; function cmp (item1, item2, propOrders) {var cps = []; // used to record the comparison results of each sorting attribute,-1 | 0 | 1. Var isAsc = true; // The sorting direction. For (var p in propOrders) {isAsc = propOrders [p] = "asc"; if (item1 [p]> item2 [p]) {cps. push (isAsc? 1:-1); break; // you can jump out of the loop, because here we know that item1 is "greater than" item2 .} Else if (item1 [p] === item2 [p]) {cps. push (0);} else {cps. push (isAsc? -1: 1); break; // can jump out of the loop. item1 "is smaller than" item2 .} }/*...*/}

Step 2: determine the final size relationship between two comparison items based on the comparison results of different sorting attributes.

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

With the above ideas, it is easy to implement the entire comparison function. below is the complete JavaScript code of the comparison function:

Comparison Functions

Function SortByProps (item1, item2) {"use strict"; var props = []; for (var _ I = 2; _ I <arguments. length; _ I ++) {props [_ I-2] = arguments [_ I];} var cps = []; // stores the result of sorting attribute comparison. // If the sorting attribute is not specified, it is sorted in ascending order of the full attribute. Var asc = true; if (props. length <1) {for (var p in item1) {if (item1 [p]> item2 [p]) {cps. push (1); break; // jump out of the loop when the value is greater .} Else if (item1 [p] === item2 [p]) {cps. push (0);} else {cps. push (-1); break; // when the value is smaller than the value, the loop exists .}}} Else {for (var I = 0; I <props. length; I ++) {var prop = props [I]; for (var o in prop) {asc = prop [o] = "asc "; if (item1 [o]> item2 [o]) {cps. push (asc? 1:-1); break; // jump out of the loop when the value is greater .} Else if (item1 [o] === item2 [o]) {cps. push (0);} else {cps. push (asc? -1: 1); break; // jumps out of the loop when the value is smaller .}}}} 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: 21}, {name: 'sharpe', value: 37}, {name: 'and', value: 45}, {name: 'eduled', value:-12}, {name: 'magnetic ', value: 21}, {name: 'zeros ', value: 37}]; function test (propOrders) {items. sort (function (a, B) {return SortByProps (a, B, propOrders) ;}); console. log (items);} function testAsc () {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/*** sorting direction. */Type Direct = "asc" | "desc";/***** sort attributes. * *** @ Interface IPropertyOrder */interface IPropertyOrder {[name: string]: Direct;}/*** simple name/value object. * *** @ Interface ISimpleObject */interface ISimpleObject {[name: string]: string | number | boolean ;} /***** sort simple name/value objects in the specified attribute and sorting direction (compare the two items in sequence according to the sorting attribute and sorting direction, and return the value representing the sorting position ). * *** @ Template T is a simple name/value object. ** @ Param {T} item1 sort and compare item 1. ** @ Param {T} item2 sort and compare item 2. ** @ Param {... IPropertyOrder []} the sorting attribute of props. ** @ Returns if item 1 is greater than item 2, return 1. If item 1 is equal to item 2, return 0. Otherwise, return-1. */Function SortByProps <T extends ISimpleObject> (item1: T, item2: T ,... props: IPropertyOrder []) {"use strict"; var cps: Array <number> = []; // stores the sorting attribute comparison result. // If the sorting attribute is not specified, it is sorted in ascending order of the full attribute. Var asc = true; if (props. length <1) {for (var p in item1) {if (item1 [p]> item2 [p]) {cps. push (1); break; // jump out of the loop when the value is greater .} Else if (item1 [p] === item2 [p]) {cps. push (0);} else {cps. push (-1); break; // when the value is smaller than the value, the loop exists .}}} Else {// sort by specified attributes and the direction of change. For (var I = 0; I <props. length; I ++) {var prop = props [I]; for (var o in prop) {asc = prop [o] = "asc "; if (item1 [o]> item2 [o]) {cps. push (asc? 1:-1); break; // jump out of the loop when the value is greater .} Else if (item1 [o] === item2 [o]) {cps. push (0);} else {cps. push (asc? -1: 1); break; // jumps out of the loop when the value is smaller .}}}} For (var j = 0; j <cps. length; j ++) {if (cps [j] = 1 | cps [j] =-1) {return cps [j];} return 0 ;}

Application scenarios and limitations

Using JavaScript on the front end to sort multiple attributes reduces requests on the server end and reduces the computing pressure on the server end. However, this method is only applicable when you only need to sort local data. If you want to sort the entire dataset by multiple attributes, you must sort the dataset at the database level on the server end.

The above section describes how to sort JavaScript Object arrays by specified attributes and sorting directions. I hope it will help you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.