我是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 (由id指示)对tutors进行排序,以便将具有所需用户ID的对象推送到tutors数组的开头。然后,我可以返回这个简单排序的数组。我想要保存的用户in列表已经存储在一个名为pinTutor的字符串数组中。以某种方式,我希望根据字符串数组pinTutor对对象数组tutors进行排序。然而,我在完成这件事上遇到了一些困难。以下是我到目前为止尝试过的一些方法:
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对数组进行排序时遇到了问题。有什么关于如何实现的建议吗?
发布于 2020-10-22 07:42:15
如果id属性是一个字符串,并且您希望根据If lexicographical顺序对数组进行排序,则可以使用:
arr.sort((a,b) => (a.id.localeCompare(b.id))); 发布于 2020-10-22 06:02:12
我假设'id‘属性是number,即使它是字符串数据类型。这对你来说应该是可行的:
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;
}请注意,typescript中number数据类型的最大数值为"9007194749250991",因此这不适用于超过8个字符的字符串。
https://stackoverflow.com/questions/64472041
复制相似问题