I'm new to React.js, and am looking for a quick and easy way to filter and sort some user data for a website that I'm building. Basically, I'm trying to find a way to sort an array of objects based on a single object property in React.js (using hooks).
I have an array of users called tutors. It's setup like this: const [tutors, setTutors] = useState<tutor[]>(null); It contains multiple instances of the tutor object, which has the following properties:
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: []
};
My goal is to sort tutors based on user ID (as indicated by id), so that objects with the desired user IDs are pushed to the start of the tutors array. I can then return this nely sorted array. I have the list of user IDs that I want to keep already stored in an array of strings called pinTutor. Somehow, I would like to sort the array of objects tutors based on the array of strings pinTutor. However, I'm having some difficulty accomplishing this. Here's some things I've tried so far:
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;
}
I'm having trouble sorting my array at the end based on the IDs. Any advice on how to implement?
Array.prototype.sort()? It has nothing to do with React and hooks specifically, though may help to solve your problem, likeconst sortedTutors = [...tutors].sort(({id:a}, {id:b}) => a-b)