Home > Blockchain >  filter array with same values
filter array with same values

Time:12-01

I need to find all employees(EmpID) with same projects(ProjectID), data will be dynamic, this array is for example.

[
  { EmpID: '143,', ProjectID: '12,', DateFrom: '2013-11-01,', DateTo: '2014-01-05\r' },
  { EmpID: '218,', ProjectID: '10,', DateFrom: '2012-05-16,', DateTo: 'NULL\r' },
  { EmpID: '143,', ProjectID: '10,', DateFrom: '2009-01-01,', DateTo: '2011-04-27' },
];

I want this array to be ->

[
  { EmpID: '218,', ProjectID: '10,', DateFrom: '2012-05-16,', DateTo: 'NULL\r' },
  { EmpID: '143,', ProjectID: '10,', DateFrom: '2009-01-01,', DateTo: '2011-04-27' },
];

CodePudding user response:

You should be able to use Array.reduce to accomplish this

// The "trick" is to pull out the first item and then use that as the match candidate
const [head, ...tail] = [{ EmpId: 1 }, { EmpId: 2 }, { EmpId: 1 }]

const output = tail.reduce(
  (acc, b) => {
    if (acc.map(o => o.EmpId).includes(b.EmpId)) {
      acc.push(b)
    }
    return acc
  },
  [head]
)

CodePudding user response:

Try something like this:

const projectEmployees = employees.filter( emp => emp.ProjectID === '12' );

See Array.filter() for the gory details.

Or... roll your own:

function selectEmployeesByProjectId( employees, id ) {
  let projectEmployees = [];
  for ( const emp of employees ) {
    if ( emp.ProjectID === id ) {
      projectEmployees.push(emp);
    }
  }
  return projectEmployees;
}

If your data is truly dynamic and you don't know its true shape, other than it's a list of objects, just make your function flexible, something like the following. [But you'll still need to know what property or properties to match against to do your filtering.

function selectMatchingObjects( listOfObjects, isWanted ) {
  return listOfObjects.filter( isWanted );
}

where isWanted is a function that accepts an object and returns a boolean true if the object is to be kept, or false if the object is to be discarded.

Once you have that you can do something like

function selectEmployeesByProject( employees , projectIdKey , projectId ) {
  const isWanted = emp = emp[projectIdKey] === projectId;
  return employees.filter( isWanted );
}

And then

const employees = getMySomeDynamicEmployees();
. . .
const projectEmployees = selectEmployeesByProject(employees, 'ProjectId', '10');
  • Related