根据通过的技能集查找具有最高技能的候选人

Find Candidate With the Highest Skills Based on Skill-Set passed

我正在使用 node.js、express.js 构建 REST API,但使用数据结构(首先没有数据库)来实现它。我有 2 条路线 PostGet。我的问题是,如何实施 get 路线,以便能够检索到作为参数传递的技能集数量最多的候选人:即

这是我的对象

const candidate = [
   {"id":1, "name":"Jonh", "skills":["Python","Java","Go","Node","Express"]},
   {"id":2, "name":"Mary", "skills":["Go","Python"]},
   {"id":3, "name":"Kevin", "skills":["Ruby","Java","Go"]}
   ]

这是 get 路线:

app.get('candidate/search', function(res,res){

 })

请帮忙

您可以使用 res.json 函数按技能对候选人进行排序,然后 return 最熟练的候选人。

skillSortFunction 将按技能数量降序排序,因此我们要选择排序数组的第一个元素。

const candidate = [
    {"id":1, "name":"Jonh", "skills":["Python","Java","Go","Node","Express"]},
    {"id":2, "name":"Mary", "skills":["Go","Python"]},
    {"id":3, "name":"Kevin", "skills":["Ruby","Java","Go"]}
];

function skillSortFunction(a, b) {
    return (b.skills || []).length - (a.skills || []).length;
}

app.get('candidate/search', function(res,res){
    candidate.sort(skillSortFunction);
    const mostSkilled = candidate[0];
    return res.json(mostSkilled);
})

原版演示 JavaScript 此处:

const candidate = [
    {"id":1, "name":"Jonh", "skills":["Python","Java","Go","Node","Express"]},
    {"id":2, "name":"Mary", "skills":["Go","Python"]},
    {"id":3, "name":"Kevin", "skills":["Ruby","Java","Go"]}
];

function skillSortFunction(a, b) {
    return (b.skills || []).length - (a.skills || []).length;
}

candidate.sort(skillSortFunction);
const mostSkilled = candidate[0];
console.log("Most skilled candidate:", mostSkilled);
const leastSkilled = candidate[candidate.length-1];
console.log("Least skilled candidate:", leastSkilled );