Home > Mobile >  Creating a filter with tags from an array of profiles
Creating a filter with tags from an array of profiles

Time:05-27

I have an array of profiles.

Each item in the array has an array of tags.

eg. devs = [ { name: "John", skills: ["react", "javascript"]}, { name: "Jane", skills: ["HTML", "javascript"]} ]

I first want to create an array of all unique skills.

Then I want to filter the devs array according to the skills I select. I want to map that array of unique skills as buttons, and when a button is clicked, filter the mapped devs array.

const devs = [ 
{ name: "John", skills: ["react", "javascript"]}, 
{ name: "Jane", skills: ["HTML", "javascript"]} ];

const allSkills = //Need all unique values from devs.skills
const [filters, setFilters] = useState([]);

return (
<> 
Filter:
{allSkills.map((skill) => <button onClick=() => setFilters(??)>{skill}</button>)}

{devs.map((dev) => <p>{dev.name} Skills:
    {dev.skills.map((skill) => <span>{skill}</span>)} 
                </p>))} //need to filter this based on filters


</>
)

It's in a React component, I took it as far as I could.

CodePudding user response:

So to get an array of unique skills you can use spread operator with concat and Set and then you can use filter method to get developers based on the selected skill.

const devs = [{
    name: "John",
    skills: ["react", "javascript"]
  },
  {
    name: "Jane",
    skills: ["HTML", "javascript"]
  }
];

const skills = Array.from(new Set([].concat(...devs.map(({ skills }) => skills))))

const  filterBySkill = (skill) => {
  return devs
    .filter(({ skills }) => skills.includes(skill))
    .map(({ name }) => name)
}

console.log(filterBySkill('javascript'))
console.log(filterBySkill('react'))
console.log(skills)

CodePudding user response:

To get list of unique skills you could use Set in combination with map e.g.

let uniqueSkills = new Set(devs.map(x=> x.skills).flat());

Then if you want to filter your inital array, you could use something like this:

let filteredList = devs.filter(x=> x.skills.includes(word));

where word is a string or a variable that containts string with concrete skill to find.

CodePudding user response:

Another alternative to the other answer if you don't want to create a Set and convert it back to array, using flat and reduce:

const devs = [ 
{ name: "John", skills: ["react", "javascript"]}, 
{ name: "Jane", skills: ["HTML", "javascript"]} ];

const allSkills = devs.map(dev => dev.skills).flat().reduce(
    (arr, val) => {
        if (!arr.includes(val)) arr.push(val); 
        return arr
    },
    []
)

console.log(allSkills)

  • Related