In practice, javascript is the most commonly used array to process multiple files, because flexibility is good enough to use, regardless of API, cookie, local storage, etc., almost used.

Here introduces Array sort, the rapid development of modern web technology, the front end often need to use non-synchronous to obtain data, get the array data, often need sorting function, ie. price sorting, new and old sort, the same type of sorting.

JavaScript

Array sort Concept

According to w3c introduced array.sort (compareFunction), the parameters brought into the different according to the needs, in addition to directly change the array data.

Sort will run the two arrays against the array to compare conditions. For example, in the following example, the first argument will be Arr[0], b will be Arr[1], and then return a.price-b.price will return a positive or negative number or 0, and then change the position according to the return value, and The right repeat runs to the fully qualified order. This is how sort is performed.

Digression below the function within the sort is run 9 times.

Ps.return is less than 0. Place a on the left b on the right,

Greater than 0 places a on the right b on the left,

Equal to 0 does not change the position.

Sort the price number array

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
let Arr = [{name:'apple',price:50},
{name:'watermelon',price:30},
{name:'mango',price:90},
{name:'banana',price:10},
{name:'peer',price:10}
];
let times = 0;
Arr.sort(function(a,b){
times ++; // 紀錄跑幾次
return a.price - b.price
}); // will run a loop comparison against the array
console.log(Arr)
// [{name: "banana", price: 10},
// {name: "peer", price: 20}
// ......
// {name: "mango", price: 90}]
console.log(times) // 9times

Sort for string name array

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
let Arr = [{name:'apple',price:50},
{name:'watermelon',price:30},
{name:'mango',price:90},
{name:'banana',price:10},
{name:'peer',price:10}
];
Arr.sort(function(a,b){
if(a.name > b.name) {
return 1; //a to the right b to the left
}else if(a.name < b.name) {
return -1; //a left b right
}else {
return 0; // unchange
}
});
console.log(Arr)
// [{name: "apple", price: 50},
// ......
// {name: "watermelon", price: 30}]

The above is sorting javascript sort, if you do not want to re-request the data, the front end can use this method to deal with the sort, if not tens of thousands of words, it can be used to use client-side performance.

It is recommended that you actually run the sort function and use the chrome debug to see what goes in the gourd.