Day 11 of 30 of JavaScript

shoyab1707

Shoyab khan

Posted on August 30, 2024

Day 11 of 30 of JavaScript

Introduction

Hey there! 👋 I hope you’re doing well. 😊 In our last post, we explored some array methods in JavaScript. Today, we’ll continue our discussion by looking at more useful array methods. Let’s get started!

Sorting an Array

Sorting an array involves arranging its elements in a specific order, whether ascending, descending, or random.

sort() Method
The sort() method sorts the elements of an array lexicographically (in dictionary order).

const fruits = ['Banana', 'Apple', 'Cherry'];
fruits.sort(); // ['Apple', 'Banana', 'Cherry']
Enter fullscreen mode Exit fullscreen mode

To sort an array in descending order, you can sort it and then reverse it:

fruits.sort().reverse(); // ['Cherry', 'Banana', 'Apple']
Enter fullscreen mode Exit fullscreen mode

Note: The sort() method modifies the original array. If you want to keep the original array unchanged, you can use the toSorted() method, which returns a new sorted array.

The sort() method uses a variant of the Timsort algorithm, which is efficient and designed to perform well on various types of data.

Numerical Sort
The sort() method works well for strings but can yield unexpected results with numbers. For example:

const numbers = [9, 67, 2];
numbers.sort(); // [2, 67, 9] (not the expected numerical order)
Enter fullscreen mode Exit fullscreen mode

To sort numbers correctly, you can provide a comparison function:

numbers.sort((a, b) => a - b); // [2, 9, 67]
Enter fullscreen mode Exit fullscreen mode

This function returns:

  • A negative number if a is less than b (meaning a comes before b).
  • Zero if they are equal.
  • A positive number if a is greater than b.

You can also use external libraries like Lodash for more advanced sorting techniques.

Finding Maximum and Minimum Elements in an Array

To find the lowest number in an array, you can use Math.min.apply():

const arr = [1, 2, 3, 4, 5];
const min = Math.min.apply(null, arr); // 1
Enter fullscreen mode Exit fullscreen mode

Similarly, to find the highest number, use Math.max.apply():

const max = Math.max.apply(null, arr); // 5
Enter fullscreen mode Exit fullscreen mode

Conclusion

That’s it for today’s blog! I hope you found this information helpful. In the next post, we’ll explore array iteration methods. Until then, stay connected, and don’t forget to follow me! 🤍

💖 💪 🙅 🚩
shoyab1707
Shoyab khan

Posted on August 30, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related