“This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”

Record knowledge and make progress every day

Definition and Usage:

The sort() method sorts the elements of an array and returns the array. The default sort order is based on the string UniCode code.

Grammar:

arrayObject.sort(sortby)

Parameters:

Sortby is optional and is used to specify the sort order, but must be a function.

Example 1:

In js we can sort the elements of an array using the sort method as follows:

Var arr =[0,1,56,23,34,3] arr.sort() console.log(arr) // Print [0,1, 23,3,34, 56]Copy the code

Explanation: : The result found in the case is not what we want, why? The reason for this is that when using sort it always uses the ASCII value of the first character for comparison sorting, so here’s how to improve ascending and descending sorting. The code improvements are as follows:

Var arr =[0,1,56,23,34,3] function sortNumber(a,b){return a-b; } arr.sort(sortNumber) console.log(arr)// Print [0, 1, 3, 23, 34, 56] function sortNumber(a,b){return b-a; } arr.sort(sortNumber) console.log(arr)// Print [56, 34, 23, 3, 1, 0]Copy the code

Example 2:

Sort by a property value in an array object

const arr2 = [ { id: 10, flag: true }, { id: 5, flag: false }, { id: 6, flag: true }, { id: 9, flag: false } ]; const r = arr2.sort((a, b) => b.flag - a.flag); // If you want to sort by id, change it to.id console.log(r); // [ // { id: 10, flag: true }, // { id: 6, flag: true }, // { id: 5, flag: false }, // { id: 9, flag: false } // ]Copy the code

Example 3:

1. Remove objects with the same name. 2. Keep the oldest objects created

Var ARr =[{name: 'Created_at ', created_at: '2021-06-04 04:54:06.164',}, {name:' Created_at ', created_at: '2021-06-04 04:52:49.753',}, {name: 'Created_at: '2021-06-04 05:02:02.398',}, {name: Created_at: '2021-06-04 04:52:40.588',}, {name: 'created_at: '2021-06-04 04:52:40.588',}, {name:' created_at: '2021-06-04 04:52:40.588', 'the 2021-06-04 05:07:21. 587'},]Copy the code

The code is as follows:

arr.reduce(function(s,v){
    var itemIdx = s.findIndex(v1=>v1.name==v.name);
    if(itemIdx == -1){
        s.push(v)
    }else{
        var item = s[itemIdx];
        if(v.created_at < item.created_at){
            s.splice(itemIdx,1,v)
        }
    }
    return s
},[])
Copy the code

Print result:

Thank you for reading. Thank you for reading