compareByPath

compareByPath

  • (path: Path, compareFn: CompareFn) => CompareFn
  1. Create a function comparing deep properties intended for built-in methods such as toSorted.

    Below, we sort an array of people by first name.

    const people = [
      { name: { first: 'mike' } },
      { name: { first: 'emma' } },
      { name: { first: 'luke' } },
    ]
    const path = ['name', 'first']
    const ascending = (left, right) => left.localeCompare(right)
    const byFirstName = compareByPath(path, ascending)
    
    const sortedPeople = people.toSorted(byFirstName)
    console.log(sortedPeople)
    // is [
    //  { name: { first: 'emma' } },
    //  { name: { first: 'luke' } },
    //  { name: { first: 'mike' } },
    // ]
    type Person = {
      name: { first: string }
    }
    const people: Person[] = [
      { name: { first: 'mike' } },
      { name: { first: 'emma' } },
      { name: { first: 'luke' } },
    ]
    const path = ['name', 'first']
    const ascending = (left: string, right: string) => left.localeCompare(right)
    const byFirstName = compareByPath(path, ascending)<Person>
    
    const sortedPeople = people.toSorted(byFirstName)
    console.log(sortedPeople)
    // is [
    //  { name: { first: 'emma' } },
    //  { name: { first: 'luke' } },
    //  { name: { first: 'mike' } },
    // ]
    
    const people = [
      { name: { first: 'mike' } },
      { name: { first: 'emma' } },
      { name: { first: 'luke' } },
    ]
    const path = ['name', 'first']
    const ascending = (left, right) =>
      left.localeCompare(right)
    const byFirstName = compareByPath(path, ascending)
    
    const sortedPeople = people.toSorted(byFirstName)
    console.log(sortedPeople)
    // is [
    //  { name: { first: 'emma' } },
    //  { name: { first: 'luke' } },
    //  { name: { first: 'mike' } },
    // ]
    type Person = {
      name: { first: string }
    }
    const people: Person[] = [
      { name: { first: 'mike' } },
      { name: { first: 'emma' } },
      { name: { first: 'luke' } },
    ]
    const path = ['name', 'first']
    const ascending = (left: string, right: string) =>
      left.localeCompare(right)
    const byFirstName = compareByPath(
      path,
      ascending
    )<Person>
    
    const sortedPeople = people.toSorted(byFirstName)
    console.log(sortedPeople)
    // is [
    //  { name: { first: 'emma' } },
    //  { name: { first: 'luke' } },
    //  { name: { first: 'mike' } },
    // ]
    
  2. We often want to sort data by a deep property. The example in 'What' shows this.

  3. Undefined properties are handled by compareByPath as defined in the spec, so compareFn will not need to handle them.