简体   繁体   中英

How to filter/sort an array of objects based on a single object property

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?

如果id属性是一个字符串,并且您想根据 ids字典顺序对数组进行排序,则可以使用:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM