[英]How to sort array of objects based on object property (which is Array) Javascript
[英]How to filter/sort an array of objects based on a single object property
我是 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
數組的開頭。 然后我可以返回這個單獨排序的數組。 我有我想要保存的用戶 ID 列表,它們已經存儲在一個名為pinTutor
的字符串數組中。 不知何故,我想根據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 對數組進行排序。 關於如何實施的任何建議?
如果id
屬性是一個字符串,並且您想根據 ids字典順序對數組進行排序,則可以使用:
arr.sort((a,b) => (a.id.localeCompare(b.id)));
我假設 '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;
}
請注意,typescript 中 Number 數據類型的最大數值為“9007194749250991”,因此這不適用於大於 8 個字符的字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.