javascript - 从对象返回最佳匹配
问题描述
在对象数组中:
const candidates = [
{
"id": "a4b7d559-8437-4bec-a6d3-65821d50a0b5",
"name": "alpha",
"skills": [
"Go",
"Ruby",
"Python"
]
},
{
"id": "a4b7d559-8437-4bec-a6d3-6554880a0b5",
"name": "metta",
"skills": [
"Express",
"Ruby",
"Python",
"swift"
]
},
{
"id": "a4b7d559-8437-4bec-a6d3-65821d50a0b5",
"name": "Thitha",
"skills": [
"Javascript",
"React",
"Express",
"Node"
]
},
]
我想编写一个函数,当我将一些技能集作为数组传递时,即["Javascript", "Express", "Node"]
返回与我的技能集匹配的候选人,在这种情况下,它将是最后一个 Thitha
。我想在req.query
我的 API 的端点中实现这个功能。请帮忙。
返回的结果将是:-
{
"id": "a4b7d559-8437-4bec-a6d3-65821d50a0b5",
"name": "Thitha",
"skills": [
"Javascript",
"React",
"Express",
"Node"
]
}
到目前为止我所尝试的: -
function getCandidate(subSet, set){
const filtered = Object.values(set).filter(key =>
subSet.includes(key)).reduce((obj, key) => {
obj[key] = set[key]
return obj
}, {})
}
解决方案
您可以执行以下操作:根据匹配的技能数量过滤和排序结果
const getCandidate = (subSet, data) => {
return data.filter(item => {
let hasSkills = 0;
item.skills.forEach(skill => {
if(subSet.includes(skill)) {
hasSkills++;
item.hasSkills = hasSkills;
}
})
return hasSkills > 0;
}).sort((a, b) => {
if(a.hasSkills > b.hasSkills) {
return -1;
}
if (a.hasSkills < b.hasSkills) {
return 1;
}
return 0;
})
}
推荐阅读
- postgresql - 如何使用postgres以递归模式获取其他记录映射的子类别ID?
- c# - 如何预热私有 ASP.NET MVC 网站?
- vue.js - vue.draggable 拖动错误的元素
- regex - 在 WSO2 流处理器/正则表达式中将文本格式转换为 json,以便在 WSO2SP 中进行自定义文本映射
- swift - 故事板中设置的图像与代码中声明的 UIImage(named: "sunrise") 对象不相等
- c++ - C++:尝试在二进制到十进制转换器中多次将非常大的整数加在一起,而您的输入是字符串值
- logstash - 用于 OASIS 日志的 GROk
- javascript - 如何在单独的页面上打印带有类的 div
- python - 如何在 Python 中使用 Azure Functions 的 Azure Blob 存储绑定将 JSON 数据上传到 Azure 存储 Blob
- javascript - 未在 Angular 8 的 Post API 调用中发送授权持有者令牌