首页 > 解决方案 > 从对象返回最佳匹配

问题描述

在对象数组中:

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
 }, {})
}

标签: javascriptarraysobject

解决方案


您可以执行以下操作:根据匹配的技能数量过滤和排序结果

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;
    })
}

推荐阅读