Search code examples
javascriptnode.jsarrayslodashjavascript-objects

Match object by array keys - Lodash


Hello i have an array of objects that looks like:

[
    {
        "id": "ae588a6b-4540-5714-bfe2-a5c2a65f547b",
        "name": "Peter casa",
        "skills": [
            "javascript",
            "es6",
            "nodejs"
        ]
    },
    {
        "id": "ae588a6b-4540-5714-bfe2-a5c2a65f547a",
        "name": "Peter Coder",
        "skills": [
            "javascript",
            "es6",
            "nodejs",
            "express"
        ]
    }
]

and i'm trying to get the best match based on skills, i'm using lodash and the idea is resolve:

passing "skills": [ "javascript", "es6", "nodejs", "express" ] get "Peter Coder" instead of "Peter casa" because the first one match all the skills in the array given, is there any lodash method to perform this?

Edit:

In this particular example, the function needs to get the candidate with is a better fit, for instance, if i pass skills: "skills": [ "javascript", "es6", "nodejs" ] even if it is a perfect match for the first one i need to choose the second because it matches the skills and has more skills, so is a better match


Solution

  • lodash has a method call intersection https://lodash.com/docs/#intersection

    you can pass the array of skill and intersect it with each developer's skill. => get the length of that intersection as score and return the one with highest score.