0

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?

2
  • Do you happen to know about Array.prototype.sort()? It has nothing to do with React and hooks specifically, though may help to solve your problem, like const sortedTutors = [...tutors].sort(({id:a}, {id:b}) => a-b) Commented Oct 21, 2020 at 21:45
  • I'm aware of that method, but wasn't sure how I to use it to sort with specific user IDs. I'm definitely trying something along those lines though, yes Commented Oct 21, 2020 at 21:53

2 Answers 2

1

If the id property is a string, and you want to sort the array based on the ids lexicographical order, you can use:

arr.sort((a,b) => (a.id.localeCompare(b.id))); 
Sign up to request clarification or add additional context in comments.

Comments

0

I assume the 'id' property is number even if it's string data type. This should work for you:

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

For 'id' as alphanumeric string, use the below code:

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

Do note that the max number value of Number datatype in typescript is "9007194749250991", so this will not work for strings larger than 8 characters.

2 Comments

It's a combination of numbers and letters, i.e. "5b1ty21f". Is there any way to sort with IDs like that?
@Alex Ross, Edited the response above as per your query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.