如何访问数组中对象的属性并对数组进行排序?

时间:2019-06-18 16:42:50

标签: javascript arrays sorting

我有一个任务-我需要按照对象的属性对对象数组进行排序。该属性由用户(以及所有对象)插入,然后应通过键对它们进行排序,该键应等于参数名称。 我插入了所有数据,但它没有执行应有的操作。请帮助我找到解决方案。

   var employees = [];
   function Employee (name, sName, age, occupation) {
       this.name = name; 
       this.sName = sName;
       this.age = age; 
       this.occupation = occupation;
       this.show = function () {
            console.log(this.name + ' ' + this.sName + ' is ' 
            + this.age + ' years old, ' + 'and he/she is a ' + this.occupation);
       }
   } 



   function createNewEmployee () {
        var anotherEmployee; 

        for (i = 0; i < Infinity; i++) {
            var newEmployee = new Employee (prompt('First Name: '), prompt('Last Name: '), +prompt('Age: '),
            prompt('Job title(occupation): '));
            if (isNaN(newEmployee.age)) {
                alert('Age is a number! Try again!');
            } else {
                employees.push(newEmployee);
            }
            anotherEmployee = prompt('Add another employee? (y/n)');
            if (anotherEmployee == 'n') { 
                for (i = 0; i < employees.length; i++) {
                    employees[i].show();
                }
                break;
            }
        }
   }

   createNewEmployee();

   // 4 

   function addSalary (employees) {

       for (i = 0; i < employees.length; i++) {
            switch (employees[i].occupation) {
                case 'director': 
                    employees[i].salary = 3000;
                    break;
                case 'manager': 
                    employees[i].salary = 1500;
                    break;
                case 'programmer': 
                    employees[i].salary = 2000;
                    break;
                default: 
                    employees[i].salary = 1000;
                    break;
            }
       }
       for (i = 0; i < employees.length; i++) {
            employees[i].show = function () {
                console.log(this.name + ' ' + this.sName + ' is ' 
            + this.age + ' years old, ' + 'and he/she is a ' + this.occupation + '.' + ' ' + 'His/Her salary is ' + this.salary + '$');
            }
            employees[i].show();
        }
   }

   addSalary(employees);


// 5  

function employeeSorting () {
    var sortedElement = prompt('What parameter should be used for sorting? (options: name, sName, age, occupation, salary)');
    if (sortedElement in employees)
        {
            if (typeof(sortedElement) == 'string') {
            function compareString (a, b) {
                var nameA = a[sortedElement].toUpperCase();
                var nameB = b[sortedElement].toUpperCase();
                if (nameA > nameB) return 1;
                if (nameA < nameB) return -1;
                return 0;
            }
            employees.sort(compareString);
            return (employees);
        } else {
            function compareNumber (a, b) {
                if (a[sortedElement] < b[sortedElement]) return 1;
                if (a[sortedElement] > b[sortedElement]) return -1;
                return 0;
            }
            employees.sort(compareNumber);
            return (employees);
            }
        } else {
        alert('You have entered an invalid parameter, please try again');
        var sortedElement = prompt('What parameter should be used for sorting? (options: name, sName, age, occupation, salary)');
    }
} 

employeeSorting(employees);

employees.forEach(function(element) {
    element.show();
})

2 个答案:

答案 0 :(得分:0)

这里是您可以采用的一种方法,它可以帮助您入门。该函数可以对具有定义的属性的对象进行排序,并接受属性名称进行排序(当前仅处理整数和字符串):

let data = [{ name: 'John', sName: 'Foo', age: 20, occupation: 'Developer', salary: 40000 },{ name: 'Bob', sName: 'Boo', age: 40, occupation: 'Chef', salary: 20000 },{ name: 'Mark', sName: 'Yu', age: 50, occupation: 'Manager', salary: 50000 }]

let sortBy = (arr, prop) => arr.sort((a,b) => Number.isInteger(a[prop])
  ? (a[prop] - b[prop])
  : a[prop].localeCompare(b[prop])
)

console.log(sortBy(data, 'age'))
console.log(sortBy(data, 'name'))
console.log(sortBy(data, 'occupation'))
console.log(sortBy(data, 'salary'))

所以您的employeeSorting函数将是这样的:

function employeeSorting () {
  var sortedElement = prompt('What parameter should be used for sorting? (options: name, sName, age, occupation, salary)');
  if (sortedElement in employees)
    return sortBy(employees, sortedElement) // <-- use sortBy here 
  else
    alert('You have entered an invalid parameter, please try again');
} 

答案 1 :(得分:0)

排序功能几乎没有问题。例如,您要检查属性名称是否存在于像sortedElement in employees这样的对象数组中。不起作用。您需要遍历此数组,然后获取给定数组条目的所有对象键,并检查它们是否包含提供的属性。

我已经从头开始重写了此功能。它可以按预期运行,并且可以直接替换而无需对代码的其他部分进行任何更改:

function employeeSorting() {
    const sortedElement = prompt('What parameter should be used for sorting? (options: name, sName, age, occupation, salary)');
    try {
        employees = employees.sort((employee1, employee2) => { //Overwrites the global employees array
            const val1 = employee1[sortedElement];
            const val2 = employee2[sortedElement];
            if (val1 === undefined || val2 === undefined) { //If a non-existing property was entered, throw an error
                throw ('You have entered an invalid parameter, please try again');
            }
            if (!isNaN(val1) && !isNaN(val2)){ //Check numbers
                return parseInt(val1) < parseInt(val2) ? -1 : parseInt(val1) > parseInt(val2) ? 1 : 0;
            } else if (typeof val1 === 'string' && typeof val2 === 'string'){ //Check strings
                return val1.toUpperCase() < val2.toUpperCase() ? -1 : val1.toUpperCase() > val2.toUpperCase() ? 1 : 0;
            } else { //Both properties had different types
                throw('There\'s a data type inconsistency between employees');
            }
        });
    } catch (error) { //Ask for the correct property name again if an error was thrown
        alert(error);
        return employeeSorting();
    }
}