Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,181 questions

56,073 answers

573 users

How to sort an array of objects that contain nested objects using custom comparison logic in TypeScript

1 Answer

0 votes
// Address type
interface Address {
    city: string;
    zip: number;
}

// Person type
interface Person {
    name: string;
    age: number;
    address: Address;
}

// Factory function for creating an Address object
function Address(city: string, zip: number): Address {
    return { city, zip };
}

// Factory function for creating a Person object
function Person(name: string, age: number, address: Address): Person {
    return { name, age, address };
}

// Print each person in a formatted line
function printPersons(people: Person[]): void {
    for (const p of people) {
        console.log(
            `${p.name} | age: ${p.age} | city: ${p.address.city} | zip: ${p.address.zip}`
        );
    }
}

// Sort persons by city, then zip, then age
function sortPersons(people: Person[]): void {
    people.sort((a: Person, b: Person) => {
        if (a.address.city !== b.address.city) {
            return a.address.city.localeCompare(b.address.city);
        }
        if (a.address.zip !== b.address.zip) {
            return a.address.zip - b.address.zip;
        }
        return a.age - b.age;
    });
}

// Sample data
const people: Person[] = [
    Person("Alice", 30, Address("San Francisco", 42100)),
    Person("Bob",   40, Address("Austin",        32000)),
    Person("Carol", 35, Address("New York City", 42000)),
    Person("Dave",  25, Address("Austin",        32000)),
    Person("Eve",   28, Address("New York City", 61000)),
];

// Perform sorting
sortPersons(people);

// Display sorted results
printPersons(people);



/*
run:

Dave | age: 25 | city: Austin | zip: 32000
Bob | age: 40 | city: Austin | zip: 32000
Carol | age: 35 | city: New York City | zip: 42000
Eve | age: 28 | city: New York City | zip: 61000
Alice | age: 30 | city: San Francisco | zip: 42100

*/

 



answered Sep 2 by avibootz

Related questions

...