JS is sorted according to an attribute of the object in the array

Time:2021-2-26

1. Code

//Sort the objects in the array are sorted alphabetically
        Compare(ticked, name) {
            return function(a, b) {
                var t1 = a[ticked];
                var s1 = a[name];
                var t2 = b[ticked];
                var s2 = b[name];
                if (t1) {
                    if (t2) {
                        return s1.localeCompare(s2);
                    } else {
                        return -1;
                    }
                } else {
                    if (!t2) {
                        return s1.localeCompare(s2);
                    } else {
                        return 1;
                    }
                }
            }
        },

2. Usage

var arr5 = [{
            id: 10,
            first:'a'
        }, {
            id: 5,
            first:'f'
        }, {
            id: 6,
            first:'j'
        }, {
            id: 9,
            first:'e'
        }, {
            id: 2,
            first:'b'
        }, {
            id: 3,
            first:'p'
        }];
        let arr = arr5.sort(this.Compare('first', 'first'))

Recommended Today

Deeply analyze the principle and practice of RSA key

1、 Preface After experiencing many dark moments in life, when you read this article, you will regret and even be angry: why didn’t you write this article earlier?! Your darkest moments include: 1. Your project needs to be connected with the bank, and the other party needs you to provide an encryption certificate. You have […]