如何基于单个对象属性对对象数组进行过滤/排序

时间:2020-10-21 21:34:26

标签: javascript arrays reactjs sorting object

我是React.js的新手,我正在寻找一种快速简便的方法来为正在构建的网站过滤和排序一些用户数据。基本上,我试图找到一种基于React.js中的单个对象属性(使用钩子)对对象数组进行排序的方法。

我有一个名为tutors的用户数组。设置如下:const [tutors, setTutors] = useState<tutor[]>(null);它包含tutor对象的多个实例,该实例具有以下属性:

export interface tutor {
  lock: boolean,
  nonce: string,
  id: string,
  first_name: string,
  last_name: string,
  bio: string,
  contact_info: any,
  setup_intent: string,
  profile_pic: string,
  default_schedule: any,
  timezone_offset: string,
  education: { school: string, degree: string }[],
  subjects: string[],
  price: number,
  zoom_link: string,
  viewed: []
};

我的目标是根据用户ID对tutors进行排序(如id所示),以便将具有所需用户ID的对象压入tutors数组的开头。然后,我可以返回此排序良好的数组。我有要保留的用户ID列表,这些ID已存储在名为pinTutor的字符串数组中。我想以某种方式基于字符串tutors对对象pinTutor的数组进行排序。但是,我在完成此任务时遇到了一些困难。到目前为止,我已经尝试过一些方法:

let arrTutors = tutors;

// Function for storing/transferring some data
function Tutor(id) {
    this.id = id;
    this.props = "";
}

// now we have tutors with IDs from "0" to "tutors.length"
for (let i = 0; i < tutors.length; i++) {
    arrTutors.push(new Tutor(i.toString()));
}

//function for sorting by pins
function sortByStar(arr){ 

    //Array for storing filtered object of arrays with userIDs from pinTutor
    let filteredtutors = []

    //Filtering
    pinTutor.forEach((tutorID) => {
        filteredtutors = arr.push(arrTutors.find(tutor => tutor.id === tutorID));
    });

    //Array for storing sorted object of arrays with userIDs from pinTutor at the start
    let sortedtutors = [];

    //Sorting
    for (let k = 0; k < tutors.length; k++) {
        for (let j = 0; j < filteredtutors.length; j++){
            if (filteredtutors[j]===tutors[k].id){
                sortedtutors = tutors.sort();
            }
        }
    }

    return sortedtutors;
}

我无法根据ID对数组进行最后排序。有关如何实施的任何建议?

2 个答案:

答案 0 :(得分:1)

如果angular-file属性是一个字符串,并且您想根据ID lexicographical的顺序对数组进行排序,则可以使用:

id

答案 1 :(得分:0)

我假设'id'属性是数字,即使它是字符串数据类型。这应该为您工作:

arr.sort((a,b) => (+a.id - +b.id)); 

对于“ id”作为字母数字字符串,请使用以下代码:

arr.sort((a,b) => (+ascii(a.id) - +ascii(b.id))); 

function ascii (str: string)  {
    str = str.toUpperCase();
    let ret : string = "";
    for (var i = 0; i < str.length; i++) {
        ret += str.charCodeAt(i);
    }
    return ret;
}

请注意,打字稿中Number数据类型的最大数字值为“ 9007194749250991”,因此,该字符串不适用于大于8个字符的字符串。