0

I have an array of objects like this ,

   let employee =  [
            {
                NodeType: "intern",
                NodeName: "Node1"
            }, {
                NodeType: "intern",
                NodeName: "Node2"
            }, {
                NodeType: "full-time",
                NodeName: "Node1"
            }, {
                NodeType: "contract",
                NodeName: "Node1"
            }
 ]

I need to be able to look through the array and see if all employees are full time then return "full time" or if the employee list is only "interns" return interns or if its mixed , return "mixed"

I tried

         var interntype = employee.find((obj) => {
                return obj.type == "intern" 
            });
         var fulltimetype = employee.find((obj) => {
                return obj.type == "full-time" 
            });
         var contracttype = employee.find((obj) => {
                return obj.type == "contract" 
            });

    if( internType) {
      return "intern";
    } else if (fulltimeType) {
          return "fullTime"
     } else return "mixed";

but is there a way where i dont do this multiple times and instead do it once

1
  • 1
    Look into the reduce function of an array. Commented Jul 3, 2017 at 21:12

1 Answer 1

3

Insert all NodeType values into a set, and check the size. If it's more than 1, return mixed, if not return the single item:

const employees = [{"NodeType":"intern","NodeName":"Node1"},{"NodeType":"intern","NodeName":"Node2"},{"NodeType":"full-time","NodeName":"Node1"},{"NodeType":"contract","NodeName":"Node1"}];

const getEmployeesType = (employees) => {
  const types = new Set(employees.map(({ NodeType }) => NodeType));
  return types.size > 1 ? 'mixed' : [...types][0];
};

console.log('mixed: ', getEmployeesType(employees));

console.log('internes: ', getEmployeesType(employees.slice(0, 2)));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.