JavaScript Array Sorting and Data Manipulation Techniques
Posted on Jun 14, 2026 in Computing and Communications
Sorting Objects by Last Name
const people = [
{ id: 1, name: "John Wilson" },
{ id: 2, name: "Emma Johnson" },
{ id: 3, name: "Michael Brown" },
{ id: 4, name: "Sophia Davis" },
{ id: 5, name: "William Zoy" },
{ id: 6, name: "Olivia Martine" },
];
people.sort((a, b) => {
let lastNameA = a.name.split(" ")[1];
let lastNameB = b.name.split(" ")[1];
return lastNameA.localeCompare(lastNameB);
});
console.log(people);
Sorting Students by Name
const students = [
{ name: "Alex", points: 31 },
{ name: "Taylor", points: 16 },
{ name: "Jamie", points: 98 },
];
const nameAscending = students.sort((a, b) => a.name.localeCompare(b.name));
console.log(nameAscending);
Sorting by Date of Birth
const students = [
{ name: "Alice", dob: "2002-05-14" },
{ name: "Bob", dob: "2001-09-22" },
{ name: "Charlie", dob: "2003-01-10" },
{ name: "Diana", dob: "2000-12-30" },
{ name: "Ethan", dob: "2002-03-18" },
{ name: "Fiona", dob: "2001-07-25" },
{ name: "George", dob: "2004-02-05" },
];
students.sort((a, b) => new Date(a.dob) - new Date(b.dob));
console.log(students);
Retrieving Customer Names by Employee ID
function getCustomerNamesByEmployeeId(employeeId) {
const employee = employees.find((employee) => employee.id === employeeId);
if (employee) {
return employee.customers.map((customer) => customer.name);
} else {
return `Employee with id ${employeeId} was not found`;
}
}
console.log(getCustomerNamesByEmployeeId(2));
console.log(getCustomerNamesByEmployeeId(10));
Finding Specific Customer by Employee ID
function getCustomerNameByEmployeeId(employeeId, customerID) {
const employee = employees.find((employee) => employee.id === employeeId);
if (!employee) {
return `Employee with id ${employeeId} does not exist`;
}
const customer = employee.customers.find((customer) => customer.id === customerID);
if (!customer) {
return `Employee with id ${employeeId} exists, but customer with id ${customerID} does not exist`;
}
return `Employee name ${employee.name}, Customer name ${customer.name}`;
}
console.log(getCustomerNameByEmployeeId(1, 1));
console.log(getCustomerNameByEmployeeId(1, 10));
console.log(getCustomerNameByEmployeeId(10, 10));