由具有相同字段值的子数组提供数组

时间:2016-07-22 10:32:23

标签: javascript

假设我有一系列课程:

Courses:
  Course:
       name: 'Bible'
       grade: 87
  Course:
       name: 'Math'
       grade: 87
  Course:
       name: 'Physics'
       grade: 87
  Course:
       name: 'Biology'
       grade: 10
  Course:
       name: 'Geography'
       grade: 10
  Course:
       name: 'Literature'
       grade: 0

我想要洗牌具有相同成绩的子课程。

例如,一个结果可能是(我只编写cources名称,但需要整个字段):

Math, Bible, Physics, Geography, Biology, Literature

另一个结果可能是:

Bible, Math, Physics, Biology, Geography, Literature

文学将在最后,因为没有其他等级等于0。

我有一个函数来填充数组(不关心子课程'成绩):

function shuffle(array) {
    var currentIndex = array.length,
        temporaryValue, randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

        // Pick a remaining element...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }

    return array;
}

数组是:

var courses = [];

courses.push(new Course('Bible', 87));
courses.push(new Course('Math', 87));
courses.push(new Course('Physics', 87));
courses.push(new Course('Biology', 10));
courses.push(new Course('Geography', 10));
courses.push(new Course('Literature', 0));

function Course(name, grade) {
    this.name = name;
    this.grade = grade;
}

这是我创建的jsfiddle:http://jsfiddle.net/Ht6Ym/3844/

任何帮助表示感谢。

2 个答案:

答案 0 :(得分:1)

您可以使用sort()方法和两个标准。

示例:

var courses = [{
       name: 'Bible',
       grade: 87
    },{
       name: 'Math',
       grade: 87
    },{
       name: 'Physics',
       grade: 87
    },{
       name: 'Biology',
       grade: 10
    },{
       name: 'Geography',
       grade: 10
    },{
       name: 'Literature',
       grade: 0
    }
  ];

courses.sort(function(a, b) {
  return a.grade < b.grade || (a.grade == b.grade && Math.random() < 0.5) ? 1 : -1;
});

console.log(courses);

答案 1 :(得分:1)

对数组

使用dynamicSort函数
function dynamicSort(property) {
    var sortOrder = 1;
    if(property[0] === "-") {
        sortOrder = -1;
        property = property.substr(1);
    }
    return function (a,b) {
        var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
        return result * sortOrder;
    }
}

console.log(courses.sort(dynamicSort("grade")).reverse());

fiddle example