0

我有一个数组如下

var myArray={};
myArray.students = [];
myArray.Professors = [];
var tmpArray1 = [];
var tmpArray2 = [];

for(var key =0; key<data.length; key++){
    tmpArray1.push(name: data.studentName,id : data.studentId);
    tmpArray2.push({name : data.profName,id :data.profId});   
    myArray.students.push({name: data.studentName,id : data.studentId});
    myArray.Professors.push({name : data.profName,id :data.profId);
}

该数组包含学生和教授的骗子。我正在尝试通过使用临时数组检查它并仅推送那些具有唯一学生 ID 和教授但它似乎无法正常工作的学生和教授来清理它。我希望 myArray 拥有独特的学生和教授

4

3 回答 3

0

假设studentIdandprofId是唯一的(而不是一对名称和 id),您可以使用类似

var myArray = {
        students: [],
        professors: []
    },
    tmpArray1 = [],
    tmpArray2 = [];

for(var key=0; key<data.length; key++){
    if(tmpArray1.indexOf(data.studentId) === -1) {
        tmpArray1.push(data.studentId);
        myArray.students.push({name: data.studentName, id: data.studentId});
    }
    if(tmpArray2.indexOf(data.profId) === -1) {
        tmpArray1.push(data.profId);
        myArray.professors.push({name: data.profName, id: data.profId);
    }
}
于 2013-10-04T17:41:26.897 回答
0

如果你想在你的数组中做一个不同的,做这个:

$(document).ready(function(){
    var data = [
        { "profId" : 1, "studentId" : 1, "profName" : "John", "studentName" : "Jack"},
        { "profId" : 2, "studentId" : 1, "profName" : "Steve", "studentName" : "Mark"},
        { "profId" : 3, "studentId" : 3, "profName" : "Gabe", "studentName" : "Martin"},
        { "profId" : 2, "studentId" : 1, "profName" : "Steve", "studentName" : "Mark"}  
    ];
    var Professors = [];
    var Students = [];

    for(var i = 0; i < data.length; i++){
        if(jQuery.inArray(data[i].profName, Professors) == -1){
            Professors.push(data[i].profName);
        }
        if(jQuery.inArray(data[i].studentName, Students) == -1){
            Students.push(data[i].studentName);
        }       
    }

    console.log("Professors:");
    for(var x = 0; x < Professors.length; x++){
        console.log("   " + Professors[x]);
    }
    console.log("Students:");   
    for(var z = 0; z < Students.length; z++){
        console.log("   " + Students[z]);
    }   
});
于 2013-10-04T17:57:19.747 回答
0

我只会使用一个对象,因为对象具有唯一的键。

var myObj={};
myObj.students = {};
myObj.professors = {};

for(var key =0; key<data.length; key++){

    myObj.students[data[key].studentId] = data[key].studentName;
    myObj.professors[data[key].profId] = data[key].profName;

}

console.log(myObj)
于 2013-10-04T18:07:42.070 回答