I have a working program that satisfies the conditions below but I'm wondering if there is a more efficient solution. Currently, I apply 4 different Javascript array method transformations which results in returning a new array for each transformation for a total of 4 new arrays. Can these transformations be combined to only create 1 additional array instead of 4 new arrays? I could chain together the calls but I was thinking it might be possible to combine them all into reduce() method but I'm not sure how that would look or if there is some better solution.
The criteria that needs to be satisfied:
- Only include employees from the Google organization but allow this to be passed as an input parameter
- Last names should be unique (no duplicate last names)
- Employees should be sorted by ID (ascending)
- Each employee should have an added property called fullName that is a combination of first and last names, separated by a space
const GOOGLE_ORG = 'Google';
const employees = [
{
id: 3,
firstName: 'John',
lastName: 'Doe',
organization: 'Google',
},
{
id: 7,
firstName: 'Jake',
lastName: 'Smith',
organization: 'Google',
},
{
id: 1,
firstName: 'Jane',
lastName: 'Doe',
organization: 'Google',
},
{
id: 2,
firstName: 'Vanessa',
lastName: 'Smith',
organization: 'Meta',
},
{
id: 5,
firstName: 'Sarah',
lastName: 'Hernandez',
organization: 'Meta',
},
{
id: 8,
firstName: 'Jessica',
lastName: 'Morales',
organization: 'Google',
},
{
id: 4,
firstName: 'Paul',
lastName: 'Stark',
organization: 'Google',
},
{
id: 6,
firstName: 'Peter',
lastName: 'Brown',
organization: 'Meta',
},
];
const transformArray = (org) => {
const filteredByOrg = employees.filter((employee) => employee.organization === org);
const addedFullName = filteredByOrg.map((employee) => ({
...employee,
fullName: employee.firstName + ' ' + employee.lastName,
}));
const uniqueByLastName = [...addedFullName.reduce((map, obj) => map.set(obj.lastName, obj), new Map()).values()];
return uniqueByLastName.sort((a, b) => a.id - b.id);
};
transformArray(GOOGLE_ORG);
map.set(obj.lastName, obj), you could writemap.set(obj.lastName, { ...obj, fullName: obj.firstName + " " + obj.lastName })and remove themap. Personally, I prefer your split approach, as it’s more readable, but I would chain method calls as much as possible. You could also consider using Iterator Helpers.