Write a javascript function to sort the lines of a string in alphabetical order.
- User
Write a javascript function to sort the lines of a string in alphabetical order.
Assistant
Here is a function to sort the lines of a string in alphabetical order:
function sortLinesAlphabetically(text) { const lines = text.split('\n'); const sortedLines = lines.slice().sort(); return sortedLines.join('\n'); }To use it:
const text = `line 3 line 1 line 2`; const sortedText = sortLinesAlphabetically(text); console.log(sortedText); // Prints: // line 1 // line 2 // line 3The key steps are:
- Split the text into lines using split('\n')
- Create a copy of the lines array using slice() so we don't mutate the original
- Sort the array using sort() which sorts strings alphabetically by default
- Join the sorted lines back into a string with join('\n')
So this takes a multi-line string, splits it into an array of lines, sorts the lines alphabetically, then joins them back into a sorted string.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.