Skip to content
Advertisement

Typescript data filtering on nested array based on another array

Im new to TS I have an array of data that looks like this

const AllJobs = [
      {
        title: Teller,
        salary: ["Hourly"],
        industries: [
          "Accounting",
          "Banking",
          "Data"
        ]
      },
      {
        title: Scientist,
        salary: ["Yearly"],
        industries: [
          "Biology",
          "Chemicals",
          "Science"
        ]
      },
        {
        title: Artist,
        salary: ["Hourly"],
        industries: [
          "Design",
          "Paint",
          "Color"
        ]
      },
    ];

let desiredSkills = ["Design","Accounting","Data"];

I want to loop over a the data in the “industries” in the AllJobs array and check if any of those vales match any of the values in desiredSkills. If no matching values, filter out that object. I don’t know if im doing this right at all.

Desired results:

 const AllJobs = [
          {
            title: Teller,
            salary: ["Hourly"],
            industries: [
              "Accounting",
              "Banking",
              "Data"
            ]
          },
            {
            title: Artist,
            salary: ["Hourly"],
            industries: [
              "Design",
              "Paint",
              "Color"
            ]
          },
        ];

Here is my previous code. That is currently not working.

const getSuggested = (item: string) => {
   const filterIndustry = this.allJobs.filter((x:any) => x['industries'].every((y: string | any[])=> y.includes(item)));
  };
this.desiredIndustries.forEach(getSuggested);

I have also tried

 const getSuggested = (item: string) => {
 let k = item;

 const data = this.allJobs.filter((item: { industries: any }) => item.industries == k);
 console.log(data);
 };
 this.desiredIndustries.forEach(getSuggested);

Advertisement

Answer

You don’t really need TypeScript here, so here’s a JS solution for you:

const AllJobs = [{
    title: 'Teller',
    salary: ['Hourly'],
    industries: ['Accounting', 'Banking', 'Data'],
  },
  {
    title: 'Scientist',
    salary: ['Yearly'],
    industries: ['Biology', 'Chemicals', 'Science'],
  },
  {
    title: 'Artist',
    salary: ['Hourly'],
    industries: ['Design', 'Paint', 'Color'],
  },
];

let desiredSkills = ['Design', 'Accounting', 'Data'];

const result = AllJobs.filter(({
  industries
}) => industries.find((industry) => desiredSkills.includes(industry)));

console.log(result);

Should be easy to translate to TS. Hope it helps!

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement