Using IF condition in Javascript's map method

The following code has the employee details
My objective : to get a new array with employee names whose job-role is Clerk

const employees = [
    {name: "ABC",  jobrole: "Officer", salary: "$200",  dob: "10-05-1990"},
    {name: "DEF",  jobrole: "Clerk", salary: "$100",  dob: "12-08-1992"},
    {name: "GHI",  jobrole: "Manager", salary: "$300",  dob: "01-01-1992"},
    {name: "JKL",  jobrole: "Clerk", salary: "$100",  dob: "12-03-1991"},
    {name: "MNO",  jobrole: "Officer", salary: "$200",  dob: "11-09-1991"},
]

console.log("Ex: Using map method to create a new Array of all the Employee names")
const mapEmployeeNames = employees.map(function(employee){
    if(employee.jobrole === "Clerk"){
        return employee.name
    }    
})

console.log(mapEmployeeNames)

The output of the above code is
Array(5) [ undefined, “DEF”, undefined, “JKL”, undefined ]

is it not possible to have an array with only the selected employee names (without the undefined) ?

map returns a new array of same size, you can couple it with filter if you want to change the array elements, and also reduce the number

1 Like

Hey thanks for your quick reply… So it is not possible to just output a particular array index ( say Jobrole in this example ) using only map right ? map only returns the whole array as a new array modified or unmodified… correct me if I’m wrong…

if you want only a single index, maybe you want to use something like find or findIndex instead?

map returns a new array of the same size

2 Likes

This code here seems to do what you want:

let arr = [];

employees.forEach(function(a){
    if(a.jobrole == 'Clerk') {
        arr.push(a.name);
    }
})

Now, here I’m creating a function where you pass:

  1. the info you want to get (name, jobrole, salary, dob)
  2. the search criteria you’d like to look for (name, jobrole, salary, dob)
  3. the value that you are looking to match (ex. “Clerk”)

And it returns your search in an array

function searchEmployees(search, criteria, value) {
    let arr = [];

    employees.forEach(function(a){
        if (a[criteria] == value) {
            arr.push(a[search]);
        }
    });

    return arr;
}

You could now try:

searchEmployees ("name", "jobrole", "Clerk"); // Gets all names whose jobrole is 'Clerk'
searchEmployees ("salary", "jobrole", "Officer"); // Gets the salaries of the Officers
searchEmployees ("dob", "salary", "$200"); // Gets dob of people who make $200

1 Like

Exactly this I wanted to know that map alone cannot return selected values…