2

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

amark
  • 71
  • 8

3 Answers3

1

You 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/

Niki van Stein
  • 10,564
  • 3
  • 29
  • 62
  • Be carefull with `.forEach()` method and its compatibility with IE8 and older browsers. – Marcos Pérez Gude Nov 20 '15 at 08:48
  • @MarcosPérezGude good point, but lets hope most people do not use ie8 anymore ;) – Niki van Stein Nov 20 '15 at 08:50
  • I wish God hears you. And IE9 / IE10 we must to kill them too. Long live to standards. – Marcos Pérez Gude Nov 20 '15 at 08:53
  • You might want to check that answer. The first line is commented and there's at least one typo. – Andy Nov 20 '15 at 08:56
  • @Andy thanks ! I am typing on phone... not the best way to type code I know. – Niki van Stein Nov 20 '15 at 08:58
  • 1
    @BasvanStein Just wanted to bring your attention to the break; as it's not compatible with forEach loops. – Mazen Elkashef Nov 20 '15 at 09:33
  • @BasvanStein also this code will never work as you are iterating through the employee property of company not the employee var. so for this to work you have to iterate through the employee var or give a short answer by alert-ing only the id. as you don't have a reference to an employee object, so alert(id) will log the employee ids – Mazen Elkashef Nov 20 '15 at 09:44
  • @lKashef thanks, the employee array is provided by the question. – Niki van Stein Nov 20 '15 at 09:51
  • @BasvanStien why it is showing undefined in alerts ?? – amark Nov 20 '15 at 09:57
  • @amark, because the alert function parameter is employee[id] when it must be only id to show the employee ids or loop again to access the employee with the right index. Assumig index 0 in the employee array is the right employee to show then we will alert(employee[0].id) – Mazen Elkashef Nov 20 '15 at 10:12
  • @BasvanStien I can see that but the index you are specifying doesn't correspond to the 0-based index of the employee obj in the employee array – Mazen Elkashef Nov 20 '15 at 10:12
  • As well as the code not working, [even if it did work](http://jsfiddle.net/su4xad31/1/) it would produce no result because there are no employees with ids equal to 5 or 9. – Andy Nov 20 '15 at 10:53
  • @Andy, you are right but is this a problem of the answer or of the question? I assume the id should be the same as the array index, if that is not the case it is not even possible to link them the way they are now. I updated my code though so it works. – Niki van Stein Nov 20 '15 at 11:09
1

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
  }
]

DEMO

Andy
  • 61,948
  • 13
  • 68
  • 95
  • 1
    That's a good answer with a good demonstration of using the filter method – Mazen Elkashef Nov 20 '15 at 10:22
  • @Andy can u please tell me why u have given [0].id in the first filter ?? – amark Nov 20 '15 at 21:07
  • `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. @amark – Andy Nov 21 '15 at 09:32
0

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]);
            }
        }
    }
}
Mazen Elkashef
  • 3,430
  • 6
  • 44
  • 72
  • Please don't go changing the names of variables in the question if answers referencing that variable have already been posted. It breaks the code in those answers. – Andy Nov 20 '15 at 09:40
  • It just made good sense but you are right! .. Thanks for the advice, I updated my answer but not sure if I can cancel my pending edit! – Mazen Elkashef Nov 20 '15 at 09:46
  • Don't worry - I had exactly the same thought. – Andy Nov 20 '15 at 09:48
  • i am a newbie to javascript never touched before so im getting confused in so many things suppose if i made a function like this: function emp(name,companies,employees){ this.name = name; this.companies = companies; this.employee = employees; } now i create a object from the above function like : var emp1 = new emp('Microsoft',companies,emplyees); now i given the company name like this, then how to get the all employees for this – amark Nov 20 '15 at 10:21
  • @amark my advice to you don't use 'this' for now as it a bit complicated and it's better to gain more ground before using it. I suggest you attend a couple of javascript courses in Udacity they are free and the Object Oriented Java course explains the 'This' parameter in details. For now my code will return an array of JSONs in console which you can view by using developer tools in a browser. You can post more details about the mark-up/HTML as well so we can better help with a more complete solution. – Mazen Elkashef Nov 20 '15 at 10:29
  • @lKashef, I would be wary of [using `for...in` loops for arrays](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea). – Andy Nov 20 '15 at 10:38
  • @Andy Can you please explain why – Mazen Elkashef Nov 20 '15 at 10:39
  • It's all explained in the link. Mostly it's not a problem, but it can throw a couple of gotchas if you're not careful which is why it's not considered good practice. – Andy Nov 20 '15 at 10:42
  • @Andy, but if I add a hasOwnProperty check I think it will be safe and ignoring the unassigned index is not bad in this case as it won't find anything, right ? .. Just making sure taking advantage of this question's example – Mazen Elkashef Nov 20 '15 at 10:55
  • @amark, yes it can and based on Andy's link it looks like a better and more safe option – Mazen Elkashef Nov 20 '15 at 17:03