在用戶物件中找到具有許多技能的人。
統計登錄用戶,統計從以下物件中得分大于等于 50 的用戶
const users = {
Alex: {
email: '[email protected]',
skills: ['HTML', 'CSS', 'JavaScript'],
age: 20,
isLoggedIn: false,
points: 30
},
Asab: {
email: '[email protected]',
skills: ['HTML', 'CSS', 'JavaScript', 'Redux', 'MongoDB', 'Express', 'React', 'Node'],
age: 25,
isLoggedIn: false,
points: 50
},
Brook: {
email: '[email protected]',
skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux'],
age: 30,
isLoggedIn: true,
points: 50
},
Daniel: {
email: '[email protected]',
skills: ['HTML', 'CSS', 'JavaScript', 'Python'],
age: 20,
isLoggedIn: false,
points: 40
},
John: {
email: '[email protected]',
skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node.js'],
age: 20,
isLoggedIn: true,
points: 50
},
Thomas: {
email: '[email protected]',
skills: ['HTML', 'CSS', 'JavaScript', 'React'],
age: 20,
isLoggedIn: false,
points: 40
},
Paul: {
email: '[email protected]',
skills: ['HTML', 'CSS', 'JavaScript', 'MongoDB', 'Express', 'React', 'Node'],
age: 20,
isLoggedIn: false,
points: 40
}
為什么我在用陣列和物件解決這類問題時會卡住?我用前端(Angular)做了很多專案,但無法解決這個問題,我知道邏輯但無法將其放入代碼中。請幫助,需要有關如何變得更好的建議,我是否需要學習演算法才能更好地解決這類問題?
uj5u.com熱心網友回復:
這就是你如何在用戶物件中獲得具有許多技能的人的方法
const compareFn = (a, b) => {
if(a[1]?.skills?.length < b[1]?.skills?.length) return 1
return -1
}
const array = Object.entries(users);
const sortedArray = array.sort(compareFn);
const person = sortedArray[0][0]; //the name of person person who has many skills
const personValues = sortedArray[0][1]; //the values of person person who has many skills
const [personName, personValues] = sortedArray[0]; //get the name and values of person
const sortedObject = Object.fromEntries(sortedArray) //Returns a sorted object
此解決方案中使用的技術
解構賦值
讓 a, b;
[a, b] = [10, 20];
控制臺.log(a); // 預期輸出:10
控制臺.log(b); // 預期輸出:20
種類
function compareFn(a, b) { if (a is less than b by some ordering criterion) { return -1; } if (a is greater than b by the ordering criterion) { return 1; } // a must be equal to b return 0; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/528736.html
