How to use Loops In Javascript

We will use a simple approach of sorting to sort the strings. In this method, we will use a loop and then compare each element and put the string at its correct position. Here we can store numbers in an array and apply this method to sort the array. 

Example: In this example, we will be using the Javascript loop to sort the elements of an array. 

javascript
// JavaScript code to sort the strings

// Function to perform sort
function string_sort (str) {
  let i = 0,
    j
  while (i < str.length) {
    j = i + 1
    while (j < str.length) {
      if (str[j] < str[i]) {
        let temp = str[i]
        str[i] = str[j]
        str[j] = temp
      }
      j++
    }
    i++
  }
}

// Driver code

// Original string
let string = ['Suraj', 'Sanjeev', 'Rajnish', 'Yash', 'Ravi']

// Print original string array
console.log('Original String')
console.log(string)

// Call string_sort method
string_sort(string)

console.log('After sorting')

// Print sorted string array
console.log(string)

Output
Original String
[ 'Suraj', 'Sanjeev', 'Rajnish', 'Yash', 'Ravi' ]
After sorting
[ 'Rajnish', 'Ravi', 'Sanjeev', 'Suraj', 'Yash' ]

Sort an array of Strings in JavaScript ?

In this article, we will sort an array of strings in Javascript. we will be given an array having strings as elements we need to sort them according to the series of A-Z.

We can sort the strings in JavaScript by the following methods described below:

Table of Content

  • Method 1: Using the sort() method
  • Method 2: Using JavaScript Loops
  • Method 3: Using the spread operator (…) and sort() method
  • Method 4: Using the localeCompare() Method

Similar Reads

Method 1: Using the sort() method

In this method, we use the predefined sort() method of JavaScript to sort the array of strings. This method is used only when the string is alphabetic. It will produce wrong results if we store numbers in an array and apply this method....

Method 2: Using JavaScript Loops

We will use a simple approach of sorting to sort the strings. In this method, we will use a loop and then compare each element and put the string at its correct position. Here we can store numbers in an array and apply this method to sort the array....

Method 3: Using the spread operator (...) and sort() method

This approach creates a shallow copy of the array using the spread operator (...) and then applies the sort() method. It ensures that the original array remains unchanged while obtaining a sorted version....

Method 4: Using the localeCompare() Method

The localeCompare() method compares two strings in the current locale, returning a number that indicates whether a reference string comes before or after or is the same as the given string in sort order. This method is particularly useful for sorting strings that may contain special characters or when sorting according to a specific locale is required....