Sorting multiple arrays at once

后端 未结 4 1078
醉酒成梦
醉酒成梦 2020-12-10 19:57

I have 3 arrays :

  • array 1 is \"Name\" John, Jim, Jack, Jill

  • array 2 is \"Age\" 25, 30, 31, 22

  • array 3 is \"Gender\" Male, Ma

4条回答
  •  余生分开走
    2020-12-10 20:23

    Having tried making objects (as suggested in some of the comments) I'm not sure the added complexity is worth it, but will post it here anyway in case it's useful. In this particular case a Person object serves little purpose and what is potentially more useful is an aggregate object (PersonSet) that will store the joint data, sort it, and deal with the lists of each type of characteristic as input and output. (jsfiddle)

    var names = ['John', 'Jim', 'Jack', 'Jill'],
        ages = [25, 30, 31, 22],
        genders = ['male', 'male', 'male', 'female'];
    function Person(name, age, gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
    function PersonSet(names, ages, genders) {
        this.content = [];
        for (var i = 0; i < names.length; i++) {
            this.content.push(new Person(names[i], ages[i], genders[i]));
            // (alternatively...)
            // this.content.push({name: names[i], age: ages[i], gender: 
            //     genders[i]});
        }
        this.sort = function(aspect) {
            this.content.sort(function(a, b) {
                return ((a[aspect] < b[aspect]) ? -1 : 
                    ((a[aspect] > b[aspect]) ? 1 : 0));
            });
        };                    
        this.get = function(aspect) {
            var r = [];
            for (var i = 0; i < this.content.length; i++) {
                r.push(this.content[i][aspect]);
            }
            return r;
        }
    }
    var personSet = new PersonSet(names, ages, genders);
    personSet.sort('age');
    console.log(personSet.get('name'), personSet.get('age'), 
                personSet.get('gender'));​​​​​​​​​​
    

提交回复
热议问题