i have two arrays variables in which each element is an object having some properties like this :
var employees = [{
name: 'Jack',
empId: 0,
age: 25,
orgId: 1
}, {
name: 'Lucifer',
empId: 1,
age: 35,
orgId: 2
}, {
name: 'Adam',
empId: 3,
age: 46,
orgId: 1
}, {
name: 'Eve',
empId: 4,
age: 30,
orgId: 3
}];
and the second variable is
var companies= [{
name: 'Microsoft',
id: 1,
employees: [5 , 9]
}, {
name: 'Google',
id: 2,
employees: [1]
}, {
name: 'LinkedIn',
id: 3,
employees: [10]
}];
so now i want that when i give a company name (for example: Google),then it will return the employee details. i want to do it by using filter()/reduce() method, but i am not able to do it . Help needed .. thank you
3 Answers 3
If the employee orgId is the same as the company id you can use filter; one to get the id, and then another to grab the employees associated with that id. The function returns an array of employees.
function getEmployees(company) {
var id = companies.filter(function (el) {
return el.name === company;
})[0].id;
return employee.filter(function (el) {
return el.orgId === id;
});
}
getEmployees('Microsoft');
OUTPUT
[
{
"name": "Jack",
"empId": 0,
"age": 25,
"orgId": 1
},
{
"name": "Adam",
"empId": 3,
"age": 46,
"orgId": 1
}
]
3 Comments
filter returns an array. Because that filter is only going to return one element matching the company name we grab the first element [0] which is an object, and then .id to get the id which we use in the second filter. @amarkYou can do that with a forEach loop and checking the name:
var Employees = []; //initialize
companies.forEach(function(company) {
if (company.name == "Microsoft"){
Employees = company.employees;
//whatever you like
Employees.forEach(function(id){
alert(id);
});
}
});
Working JsFiddle: https://jsfiddle.net/sapyt777/
13 Comments
.forEach() method and its compatibility with IE8 and older browsers.Trying to brush-up my skills. So I'm pretty sure it works but I don't know if it's a good way to achieve what you want!
var input = "Microsoft";
for(company in companies) {
if(companies[company].name === input) {
for(emp in employee) {
if(companies[company].id === employee[emp].orgId)
{
console.log(employee[emp]);
}
}
}
}