Sort an Array in n8n

Difficulty
1/10
Tags
arrayssortingexpressions

Your boss wants you to create a workflow that outputs an array (a list of items) of strings: ['1', '4', '2']. You need to sort it.

Sorting data is a common task in automation—whether you're organizing names alphabetically, prioritizing tasks by date, or arranging numbers for reports.

n8n expressions are small code snippets you write directly in node fields, wrapped in {{ }}. They support full JavaScript, so you can use built-in methods like .sort() to manipulate your data without needing a separate Code node.

When you type a . after your data (like $json.input.), you'll see a list of available methods. These are built-in functions that manipulate your data in different ways. For this challenge, we'll use .sort() to reorder the array.

What you'll practice:

  • Using JavaScript array methods in n8n expressions
  • Using the Edit Fields (Set) node to transform data before passing it to the next step

Hints

  1. Add an Edit Fields (Set) node after the existing node
  2. Create a new field called input_sorted
  3. Use the .sort() method on $json.input inside an expression

Note: .sort() sorts alphabetically by default. For numeric sorting, you'd use .sort((a, b) => a - b).

Explanation

The solution adds an Edit Fields (Set) node with a new field input_sorted that uses the expression:

{{ $json.input.sort() }}

JavaScript's .sort() method sorts arrays alphabetically by default. Since these are strings, ['1', '4', '2'] becomes ['1', '2', '4'].

Note: For numeric sorting, you'd need a custom comparator: .sort((a, b) => a - b)

Login to see the exercise

Create an account to access challenges and track your progress.

Log in to see exercise