2016-07-22 153 views
1

假设其子排列我的课程的数组:Suffle阵列由具有相同的字段值

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/

任何帮助理解。

+1

可以请你告诉数组 – brk

+0

@ user21813 97,我已经更新了我的主题。谢谢! –

+1

先洗牌,然后按等级分类。 – JJJ

回答

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);

+2

回调应该返回'-1','0'或'1',而不是布尔值。 – deceze

+1

谢谢。这是固定的。 – Arnauld

+0

谢谢,它的作品! –

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

+0

谢谢,但排序返回相同的结果: “物理”,“数学”,“圣经”,“地理”,“生物学”,“文学”。 –