Home > Article > Web Front-end > Solve the problem that array sorting in JavaScript does not change
I was working on a project recently. After Ajax returned data from the background, when the front-end was processed with js, I found that no matter how sort was used, there would be no change in the end. Or only change the last sorting. After struggling for a long time, I finally checked the information and found that there is a distinction between shallow copy and deep copy in js.
var provinceConfirmedCount = data; var provinceDeadCount = data; var provinceCuredCount = data; provinceConfirmedCount.sort(sortBy(("provinceConfirmedCount"))); provinceDeadCount.sort(sortBy(("provinceDeadCount"))); provinceCuredCount.sort(sortBy(("provinceCuredCount"))); console.log(provinceConfirmedCount); //不生效 console.log(provinceDeadCount); //不生效 console.log(provinceCuredCount); //生效 //比较数组对象 function sortBy(field) { return function(a,b) { return parseInt(b[field]) - parseInt(a[field]); } }
Shallow copy, deep copy and assignment
The difference between these three cannot be how the data is changed, for the sake of simplicity Clearly, use a table to understand the fastest:
whether it points to the same object | The first layer is the basic data type | The original data contains sub-objects | |
Assignment | Yes | Will cause the original data to change together | Will cause the original data to change together |
Shallow copy | No | Will not cause the original data to change at the same time | Will cause the original data to change at the same time |
Deep copy | Yes | No Make the original data change together | Will not make the original data change together |
Solution
Now that we know the principle, the requirements here need to be completely changed, so we can use the extend method in JQuery to handle it:
var provinceConfirmedCount = $.extend([], data); var provinceDeadCount = $.extend([], data);; var provinceCuredCount = $.extend([], data);; provinceConfirmedCount.sort(sortBy(("provinceConfirmedCount"))); provinceDeadCount.sort(sortBy(("provinceDeadCount"))); provinceCuredCount.sort(sortBy(("provinceCuredCount"))); console.log(provinceConfirmedCount); console.log(provinceDeadCount); console.log(provinceCuredCount);
Syntax: $.extend(target, [object1], [objectN]) Among them, target is the target type. Here I use array [], it can also be {}, which can be processed according to the actual situation. From the following [object1], [objectN] we can know that extend can merge multiple objects to be processed into an object of the target type.
Recommended tutorial: "JS Tutorial"
The above is the detailed content of Solve the problem that array sorting in JavaScript does not change. For more information, please follow other related articles on the PHP Chinese website!