How to apply dynamic values for filtering in TypeScript?

My task is to filter out all Portfolio Lead who have English Competency set to No.

 var data = [{
    "Employee Number": 138,
    "English Competency": "No",
    "Portfolio Lead": "x",
    "Maths Competency": "No"
  },
  {
    "Employee Number": 1385,
    "English Competency": "yes",
    "Portfolio Lead": "x",
    "Maths Competency": "yes"
  },
  {
    "Employee Number": 1318,
    "English Competency": "yes",
    "Portfolio Lead": "y",
    "Maths Competency": "No"
  },
  {
    "Employee Number": 1388,
    "English Competency": "No",
    "Portfolio Lead": "y",
    "Maths Competency": "yes"
  },
  {
    "Employee Number": 1388,
    "English Competency": "No",
    "Portfolio Lead": "z",
    "Maths Competency": "no"
  }
];

******************UPDATE********************************

Although the code below is functioning correctly, it is only displaying the employee number in the employeeData instead of the full data. Assistance is appreciated.

var leadsList = ['x','y','z']

function getcompetencyData(name) {

  let filteredCompetency = data.filter(item => item[name] == "No");
  console.log(filteredCompetency);

  let leadData = [];
  let employeeData = [];
  leadsList.forEach(lead => {
    filteredCompetency.forEach(competency => {
      if (lead === competency["Portfolio Lead"]) {
        leadData.push({ "Portfolio Lead": lead, "employeeData": employeeData.push(competency) })
      }
    })
  });
  console.log(leadData);
}

getcompetencyData('English Competency');

Please advise on any mistakes in the code. The stackblitz link for reference can be found below.

https://stackblitz.com/edit/typescript-n5j5y6

Answer №1

Give this a shot.

var employees = [{
    "Employee Number": 138,
    "English Competency": "No",
    "Portfolio Lead": "x",
    "Maths Competency": "No"
  },
  {
    "Employee Number": 1385,
    "English Competency": "yes",
    "Portfolio Lead": "x",
    "Maths Competency": "yes"
  },
  {
    "Employee Number": 1318,
    "English Competency": "yes",
    "Portfolio Lead": "y",
    "Maths Competency": "No"
  },
  {
    "Employee Number": 1388,
    "English Competency": "No",
    "Portfolio Lead": "y",
    "Maths Competency": "yes"
  },
  {
    "Employee Number": 1388,
    "English Competency": "No",
    "Portfolio Lead": "z",
    "Maths Competency": "no"
  }
];

let leadX = [];
let leadY = [];
let leadZ = [];

function sortEmployees(key, value) {
    employees.map(employee => {
        if(employee[key] === value) {
         if (employee['Portfolio Lead'] === 'x') return leadX.push(employee)
         if (employee['Portfolio Lead'] === 'y') return leadY.push(employee)
         if (employee['Portfolio Lead'] === 'z') return leadZ.push(employee)  
        }
        return
    })
}

sortEmployees('Maths Competency', 'No');
console.log(leadX, leadY, leadZ);

also

sortEmployees('English Competency', 'No');
console.log(leadX, leadY, leadZ);

Alternatively, you can also pass the Portfolio Lead value as an argument in the function. Let me know if you still have questions.

Answer №2

To ensure accurate results, consider creating two separate objects filled with data based on iterative population.

The response provided previously may yield incorrect outcomes if the lists x, y, and z are not cleared. It would be more effective to follow this approach:

const data = [
  {
    "Employee ID": 138,
    "Language Proficiency": "No",
    "Project Lead": "x",
    "Math Proficiency": "No"
  },
  {
    "Employee ID": 1385,
    "Language Proficiency": "yes",
    "Project Lead": "x",
    "Math Proficiency": "yes"
  },
  {
    "Employee ID": 1318,
    "Language Proficiency": "yes",
    "Project Lead": "y",
    "Math Proficiency": "No"
  },
  {
    "Employee ID": 1388,
    "Language Proficiency": "No",
    "Project Lead": "y",
    "Math Proficiency": "yes"
  },
  {
    "Employee ID": 1388,
    "Language Proficiency": "No",
    "Project Lead": "z",
    "Math Proficiency": "no"
  }
];

// Initialize empty objects to accumulate results
const Language = {}
const Math = {}

// Loop through each data entry
for (let entry of data) {
  // Assign properties to variables for ease of use
  id = entry["Employee ID"]
  lang = entry["Language Proficiency"]
  lead = entry["Project Lead"]
  math = entry["Math Proficiency"]

  // Create empty lists for Language and Math objects if key is absent
  if (!Language[lead]) {
    Language[lead] = []
  }
  if(!Math[lead]) {
    Math[lead] = []
  }

  // Add employee to lists based on language and math proficiency per lead
  if (lang == "yes") {
    Language[lead].push(id)
  }
  if (math == "yes") {
    Math[lead].push(id)
  }
}

// Display language proficiency results
console.log("Project Lead: | Language Proficiency:")
for (let [lead, emps] of Object.entries(Language)) {
  console.log(lead, "       ",emps.length)
}
// Display math proficiency results
console.log("Project Lead: | Math Proficiency:")
for (let [lead, emps] of Object.entries(Math)) {
  console.log(lead, "       ",emps.length)
}

Answer №3

An Easy Method utilizing filter and map for data transformation:

function getIncompetentEmployees(){

var data = [{
    "Employee ID": 138,
    "English Skill Level": "Poor",
    "Manager": "A",
    "Math Skill Level": "Basic"
  },
  {
    "Employee ID": 1385,
    "English Skill Level": "Excellent",
    "Manager": "B",
    "Math Skill Level": "Advanced"
  },
  {
    "Employee ID": 1318,
    "English Skill Level": "Good",
    "Manager": "C",
    "Math Skill Level": "Basic"
  },
  {
    "Employee ID": 1388,
    "English Skill Level": "Poor",
    "Manager": "D",
    "Math Skill Level": "Advanced"
  },
  {
    "Employee ID": 1388,
    "English Skill Level": "Poor",
    "Manager": "E",
    "Math Skill Level": "None"
  }];

  return data.filter(item =>{
        return item['English Skill Level'] === 'Poor' ? item : false
      }).
                  map((item) => {
                    return {
                      ['English Skill Level']:item['English Skill Level'],
                      ['Manager']: item['Manager']
                    }
                  });     
}   

var employeesList = getIncompetentEmployees();
console.log(employeesList);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can I use Javascript to access a span element by its class name?

Similar Question: How to Retrieve Element By Class in JavaScript? I am looking to extract the text content from a span element that does not have an ID but only a specific class. There will be only one span with this particular class. Can anyone guide ...

Error: Unable to locate module adaptivecards-templating

After adding the module through the command: npm install adaptive-expressions adaptivecards-templating --save and importing it, I encountered an error when trying to run my application: ...

Ways to sort through an array to find distinct values and sum up the repeated ones in PHP

The data is sourced from an API, so I have no control over it. Before obtaining this result, I used json_decode($response, true) - Array ( [0] => Array ( [status] => ok [res] => Array ...

Storing additional data from extra text boxes into your database can be achieved using AJAX or PHP. Would you

A dynamic text box has been created using Jquery/JavaScript, allowing users to click on an "Add More" button to add additional input boxes for entering data. However, a challenge arises when attempting to store this user-generated data in a database. Assi ...

Using the Ngclass function with a pair of objects

Can you include 2 objects in an ngclass function like this? <div class="progress-bar"[ngClass]="getProgressValues(obj.val1,obj.val2)"> </div> I am encountering a JSON error. SyntaxError: JSON.parse: bad control character in string literal at l ...

How can I retrieve a certain type of object property in TypeScript?

Imagine having a collection of flags stored in an object like the example below: type Flags = { flag1: string, flag2: string, flag3: boolean, flag4: number } // const myFlags: Flags = { // flag1: 'value 1', // flag2: 'value 1&ap ...

navigate to a different section on the page with a series of visuals preceding it

When I try to navigate to a specific dom element on another page, the page initially works fine but then jumps to somewhere before that element. I believe this issue occurs because the page calculates the position before images load, and once the images ar ...

Substitute commas with spaces in the material chips

I am using the material angular chips input. Here is how I am displaying the data: <div [ngStyle]="{'font-size':'18px'}" *ngFor="let ppsToDisplay of ppssToDisplay | async"> <mat-list *ngIf="ppsToDisplay.effetsind" > ...

Dynamic array of opaque pointers in C

Alright, I have some C code that looks like this: //for malloc #include <stdlib.h> //to define the bool type #if __STDC_VERSION__ >= 199901L #include <stdbool.h> #else typedef int bool; #endif //define structs typedef struct A{ int int ...

Retrieve a result by utilizing a nested function in conjunction with the request NPM module

Hello there! I'm currently working on scraping data from the ghost blogging platform using the request package. However, I've run into a bit of a roadblock when trying to return a value of a nested request. I've pinpointed the area that seem ...

Dynamic tag names can be utilized with ref in TypeScript

In my current setup, I have a component with a dynamic tag name that can either be div or fieldset, based on the value of the group prop returned from our useForm hook. const FormGroup = React.forwardRef< HTMLFieldSetElement | HTMLDivElement, React. ...

The request to http://localhost:3000/cartdata has encountered an internal server error (500) in the isAxiosError.js file at line

Error Image I'm currently working on developing a shopping cart feature, and I've encountered an issue when transferring data from the client side to the server side. Despite the cart data being successfully updated in the session, an internal se ...

The res.send() method in Restify was not triggered within the callback function of an event

Currently, I am utilizing restify 2.8.4, nodejs 0.10.36, and IBM MQ Light messaging for a RPC pattern. In this setup, when the receiver has the result ready, it emits an event. The below restify POST route is supposed to capture this event along with the ...

The issue of JQuery selector failure within an AngularJS controller

In my current setup, I have viewA along with ControllerA. However, when an image is clicked on viewA, I need to switch over to another ViewB along with its corresponding ControllerB. In ViewB, there are multiple checkboxes which the user can interact wit ...

Methods for adjusting data based on the current user's login

I'm currently working on integrating a user login feature using Angular 6 for a stock management system. The user credentials are saved in the database, and I have successfully retrieved them into a component (login) for validation. After a successful ...

How can checkboxes be combined from two separate tables?

Within this interactive code example, you will find two tables containing checkboxes in each row. Upon clicking the To button, a dialog box will appear allowing you to select users or groups from a drop-down menu. The corresponding tables will then be dis ...

Unordered calling of functions in JavaScript - is it possible?

I'm currently working on a project that involves extracting data from an SQL database and converting the output of a query (which is a number) into a corresponding color, which is then passed to a JavaScript variable. Essentially, I am using ajax to ...

Encountered a server issue (500 Internal Server Error) when attempting to send a POST

I have been working on a social media app project using React and MongoDB. However, every time I try to register a user, I encounter a POST error in the console. I have reviewed both my client-side and server-side code, but I am still unable to successfull ...

How can I access an object in ng-model in AngularJS?

When a user selects a client from the list, I want to display the client's ID and country. Currently, I can display the entire selected object but not the specific client details. <label class="control-label red">Client</label> ...

access older siblings, accordion animation

I need assistance achieving an accordion effect on a DIV when hovering over it. The right side of the accordion is functioning properly, but I am facing issues with the left side. You can view my code on jsFiddle Could someone please provide guidance on ...