-1

In Next.js site (here https://nextjs.org/learn/basics/data-fetching/implement-getstaticprops), this example :

import path from 'path'
import matter from 'gray-matter'

const postsDirectory = path.join(process.cwd(), 'posts')

export function getSortedPostsData() {
  // Get file names under /posts
  const fileNames = fs.readdirSync(postsDirectory)
  const allPostsData = fileNames.map(fileName => {
    // Remove ".md" from file name to get id
    const id = fileName.replace(/\.md$/, '')

    // Read markdown file as string
    const fullPath = path.join(postsDirectory, fileName)
    const fileContents = fs.readFileSync(fullPath, 'utf8')

    // Use gray-matter to parse the post metadata section
    const matterResult = matter(fileContents)

    // Combine the data with the id
    return {
      id,
      ...matterResult.data
    }
  })
  // Sort posts by date
  return allPostsData.sort(({ date: a }, { date: b }) => {
    if (a < b) {
      return 1
    } else if (a > b) {
      return -1
    } else {
      return 0
    }
  })
}

In this example the return value of function getSortedPostsData() is a sorted list of allPostsData. Posts are sorted on the basis of date.

My question is how the array is being sorted ?

The sort function is taking two arguments {date:a} , {date:b}. Is it automatically converting the arguments to Date Object as the a.date and b.date are strings

Ishan Bassi
  • 490
  • 1
  • 5
  • 13
  • They are destructuring the `date` property of 2 objects being compared to `a` and `b` variables. Can you please add the sample values for `allPostsData` with the `date` property? – adiga Aug 17 '21 at 06:54
  • "*Is it automatically converting the arguments to Date Object as the a.date and b.date are strings*" no, why would it? There is nothing telling JS that the strings represent dates. They are just compared as strings. – VLAZ Aug 17 '21 at 06:54
  • @adiga here they are : `{ id: 'ssg-ssr', title: 'When to Use Static Generation v.s. Server-side Rendering', date: '2020-01-02' } { id: 'pre-rendering', title: 'Two Forms of Pre-rendering', date: '2020-01-01' }` – Ishan Bassi Aug 17 '21 at 07:19

1 Answers1

0

This answer shows which sorting algorithm is used for each situation.

It is not automatically converting the arguments to Dates. That must be done beforehand. If you say that Date a and b are strings, they will be compared lexicographicaly according to the callback provided to the sort function.

Tobias S.
  • 21,159
  • 4
  • 27
  • 45