Tutorial: Sorting In Javascript
Tags: javascript, programming, webdev, codenewbie
Published: 2022-01-22 10:28:35

---
title: Tutorial: Sorting In Javascript
published: True
date: 2021-01-10 01:16:04 UTC
tags: ["JavaScript", "Programming", 'webdev', 'codenewbie']
canonical_url: https://www.devwares.com/blog//javascript-sort
---

## JavaScript Sorting Arrays


**Sorting an Array**

The sort() method alphabetically sorts an array:

**JavaScript Code:**

```javascript
var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
fruits.sort(); // Sorts the elements of fruits

```

**Reversing an Array** The reverse() method reverses an array's elements. It can be used to sort an array in descending order as follows:

**JavaScript Code:**

```javascript
var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
fruits.sort(); // First sort the elements of fruits
fruits.reverse(); // Then reverse the order of the elements

```

**Numeric Sort:** The sort() function arranges data as strings by default. This is great for strings ("Apple" comes before "Banana"). When numbers are arranged as strings, however, "25" is more than "100," because "2" is greater than "1." As a result, when sorting numbers, the sort() method will return an inaccurate result. This can be remedied by including a comparison function:

**JavaScript Code:**

```javascript
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b) {
  return a - b;
});

```

Use the same trick to sort an array descending:

**JavaScript Code:**

```javascript
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b) {
  return b - a;
});

```

**The Compare Function** The comparison function's goal is to define a different sort order. Depending on the arguments, the comparison function should return a negative, zero, or positive value:

`function(a, b){return a - b}`

When the sort() method compares two numbers, it passes them to the compare function, which sorts them based on the (negative, zero, positive) value returned. If the outcome is negative, an is ranked first, followed by b. If the outcome is positive, b is ranked first, followed by a. If the result is 0, no modifications to the two values' sort order are made.

**Example:** The compare function compares two values at a time throughout the entire array (a, b). The sort() method uses the compare function to compare 40 and 100. (40, 100). The sort function sorts 40 as a number less than 100 since the function calculates 40 - 100 (a - b) and the result is negative (-60). You may play about with numerical and alphabetical sorting using this code snippet:

```javascript
<button onclick="myFunction1()">Sort Alphabetically</button>
<button onclick="myFunction2()">Sort Numerically</button>
<p id="demo"></p>

<script>
    var points = [40, 100, 1, 5, 25, 10];
    document.getElementById("demo").innerHTML = points;
    function myFunction1() {
      points.sort();
      document.getElementById("demo").innerHTML = points;
    }
    function myFunction2() {
      points.sort(function(a, b){return a - b});
      document.getElementById("demo").innerHTML = points;
    }
</script>

```

**Sorting an Array in Random Order**

**JavaScript Code:**

```javascript
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b) {
  return 0.5 - Math.random();
});

```

**The Fisher Yates Method**

The array.sort() function in the above code is not accurate; it favors some values over others. The Fisher Yates shuffle is the most popular right method, and it was first used in data science in 1938! The method can be converted into JavaScript as follows:

**JavaScript Code:**

```javascript
var points = [40, 100, 1, 5, 25, 10];
for (i = points.length - 1; i > 0; i--) {
  j = Math.floor(Math.random() * i);
  k = points[i];
  points[i] = points[j];
  points[j] = k;
}

```

**Find the Highest (or Lowest) Array Value**

In an array, there are no built-in functions for finding the maximum or minimum value. You can use the index to get the highest and lowest values after you've sorted an array.

**Sorting ascending:**

**JavaScript Code:**

```javascript
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b) {
  return a - b;
});
// now points[0] contains the lowest value
// and points[points.length-1] contains the highest value

```

**Sorting descending:**

**JavaScript Code:**

```javascript
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b) {
  return b - a;
});
// now points[0] contains the highest value
// and points[points.length-1] contains the lowest value

```

If you only want to find the top (or lowest) value, sorting an entire array is wasteful.

**Using Math.max() on an Array:**To determine the highest number in an array, use Math.max.apply:

**JavaScript Code:**

```javascript
function myArrayMax(arr) {
  return Math.max.apply(null, arr);
}
Math.max.apply(null, [1, 2, 3]) is equivalent to Math.max(1, 2, 3).

```

**Using Math.min() on an Array:**To determine the lowest value in an array, use Math.min.apply:

**JavaScript Code:**

```javascript
function myArrayMin(arr) {
  return Math.min.apply(null, arr);
}

Math.min.apply(null, [1, 2, 3]) is equivalent to Math.min(1, 2, 3).

```

**My Min / Max JavaScript Methods**

Using a "home-made" approach is the quickest solution. This function iterates across an array, comparing each value to the highest value found:

**JavaScript Code: (Find Max)**

```javascript
function myArrayMax(arr) {
  var len = arr.length;
  var max = -Infinity;
  while (len--) {
    if (arr[len] > max) {
      max = arr[len];
    }
  }
  return max;
}

```

This function iterates across an array, comparing each value to the lowest value found:

**JavaScript Code: (Find Min)**

```javascript
function myArrayMin(arr) {
  var len = arr.length;
  var min = Infinity;
  while (len--) {
    if (arr[len] < min) {
      min = arr[len];
    }
  }
  return min;
}

```

**Sorting Object Arrays:** Objects are frequently found in JavaScript arrays

**JavaScript Code:**

```javascript
var cars = [
  { type: 'Volvo', year: 2016 },
  { type: 'Saab', year: 2001 },
  { type: 'BMW', year: 2010 },
];

```

The sort() method can be used to sort an array even if its properties are of different data types. To compare the property values, write a compare function like follows:

**JavaScript Code:**

```javascript
cars.sort(function(a, b) {
  return a.year - b.year;
});

```

It's a little trickier to compare string properties:

**JavaScript Code:**

```javascript
cars.sort(function(a, b) {
  var x = a.type.toLowerCase();
  var y = b.type.toLowerCase();
  if (x < y) {
    return -1;
  }
  if (x > y) {
    return 1;
  }
  return 0;
});

```


[![Contrast Bootstrap UI Kit](https://www.devwares.com/static/6b149e3d75b230f7e8452ace9e21bb05/587b0/banner-ad-1.png "Contrast Bootstrap UI Kit")](https://www.devwares.com/product/bootstrap-contrast-pro)

## Resources

You may find the following resources useful:

- [Get Contrast PRO](https://www.devwares.com/product/contrast-pro)
- [Html 5 Basic Example](https://www.devwares.com/blog/html-basic-example)
- [Including JavaScript in your HTML project](https://www.devwares.com/blog/html-javascript)
- [Tutorial: JavaScript Data Output](https://www.devwares.com/blog/javascript-display)
- [Tutorial: JavaScript Events](https://www.devwares.com/blog/javascript-events)
- [Contrast Installation](https://www.devwares.com/docs/contrast/react/Installation/)
- [Charts](https://www.devwares.com/docs/contrast/react/chart/)
- [Accordion](https://www.devwares.com/docs/contrast/react/components/accordion/)
- [Alert](https://www.devwares.com/docs/contrast/react/components/alert/)
- [Animation](https://www.devwares.com/docs/contrast/react/components/animations/)
- [Autocomplete](https://www.devwares.com/docs/contrast/react/components/autocomplete/)
- [Badges](https://www.devwares.com/docs/contrast/react/components/badge/)
- [Box](https://www.devwares.com/docs/contrast/react/components/box/)
- [Breadcrumb](https://www.devwares.com/docs/contrast/react/components/breadcrumb/)
- [ButtonGroup](https://www.devwares.com/docs/contrast/react/components/buttonGroup/)
- [ButtonToolbar](https://www.devwares.com/docs/contrast/react/components/buttonToolbar/)
- [Button](https://www.devwares.com/docs/contrast/react/components/buttons/)
- [Card](https://www.devwares.com/docs/contrast/react/components/card/)
- [Carousel](https://www.devwares.com/docs/contrast/react/components/carousel/)
- [Checkbox](https://www.devwares.com/docs/contrast/react/components/checkbox/)
- [Collapse](https://www.devwares.com/docs/contrast/react/components/collapse/)
- [DropDown](https://www.devwares.com/docs/contrast/react/components/dropdown/)
- [Footer](https://www.devwares.com/docs/contrast/react/components/footer/)
- [Icon](https://www.devwares.com/docs/contrast/react/components/icon/)
- [Iframe](https://www.devwares.com/docs/contrast/react/components/iframe/)
- [Input](https://www.devwares.com/docs/contrast/react/components/input/)
- [InputGroup](https://www.devwares.com/docs/contrast/react/components/inputgroup/)
- [ListGroup](https://www.devwares.com/docs/contrast/react/components/listgroup/)
- [Mask](https://www.devwares.com/docs/contrast/react/components/mask/)
- [Modal](https://www.devwares.com/docs/contrast/react/components/modal/)
- [Multiselect](https://www.devwares.com/docs/contrast/react/components/multiselect/)
- [Notification](https://www.devwares.com/docs/contrast/react/components/notification/)
- [Pane](https://www.devwares.com/docs/contrast/react/components/pane/)
- [Panel](https://www.devwares.com/docs/contrast/react/components/panels/)
- [Progress](https://www.devwares.com/docs/contrast/react/components/progress/)
- [Radio](https://www.devwares.com/docs/contrast/react/components/radio/)
- [Rating](https://www.devwares.com/docs/contrast/react/components/rating/)
- [Select](https://www.devwares.com/docs/contrast/react/components/select/)
- [Select 2](https://www.devwares.com/docs/contrast/react/components/select2/)
- [SmoothScroll](https://www.devwares.com/docs/contrast/react/components/smoothscroll/)
- [Slider](https://www.devwares.com/docs/contrast/react/components/slider/)
- [Spinner](https://www.devwares.com/docs/contrast/react/components/spinner/)
- [Stepper](https://www.devwares.com/docs/contrast/react/components/stepper/)
- [Switch](https://www.devwares.com/docs/contrast/react/components/switch/)
- [Navbar](https://www.devwares.com/docs/contrast/react/navigation/navbar/)
- [Pagination](https://www.devwares.com/docs/contrast/react/navigation/pagination/)
- [Sidebar](https://www.devwares.com/docs/contrast/react/navigation/sidebar/)
- [Tab](https://www.devwares.com/docs/contrast/react/navigation/tabs/)
- [Date Picker](https://www.devwares.com/docs/contrast/react/sections/datepicker/)
- [FileUploader](https://www.devwares.com/docs/contrast/react/sections/fileuploader/)
- [Time Picker](https://www.devwares.com/docs/contrast/react/sections/timepicker/)
- [Editable Table](https://www.devwares.com/docs/contrast/react/table/editabletable/)
- [Table](https://www.devwares.com/docs/contrast/react/table/table/)
- [Data Table](https://www.devwares.com/docs/contrast/react/table/datatables/)
- [Widgets]
(https://www.devwares.com/docs/contrast/react/widgets/)
- [Forms]
(https://www.devwares.com/docs/contrast/react/forms/)