Kriza Educa

Kriza Educa

1576084455

Sorting Method of Arrays in JavaScript

Understanding the Sort Method of Arrays. How to use JavaScript’s sort?

  • The JavaScript array sort() is used to sort array elements.
  • By default, the array will sort in ascending order, but we can change it.
  • This method willchange the original array.
  • We can also provide our comparing function to implement custom sorting.
var array = [1,2,3,1,2,3];

array.sort(); [1,1,2,2,3,3]

Let’s try another example:

var array = [1,2,11];

array.sort(); // [1,11,2]

For the above code, the expected result is [1,2,11], but we get [1,11,2]. The reason is the sort method converts the elements into strings then compares their sequences of UTF-16 code units values.

So the 11 is converted to “11”. When we compare two strings like “11” and “2”, the char code is compared means char code of 1 is 49 , whereas char code of 2 is 50. Because of 49 < 50, we get [1,11,2].

If the array contains any undefined, then all undefined elements are sorted to the end of the array. We can use the default sort method to sort strings.

var names = ["John", "Abu", "Babu", "Balu", "Antony"]

names.sort();

console.log(names); // ["Abu", "Antony", "Babu", "Balu", "John"]

For other types, we need to pass our compareFunction as an argument to sort Function. The compare function takes two arguments. The two arguments are taken as from array on index [0,1] , [1,2] … [arrayLength-2, arrayLength-1] for comparing the pair of elements.

The sorting of elements is based on the return value of compareFunction for each pair of comparison. If the function returns…

  • >0 then the position of a and b is swapped.
  • <=0 then there is no change in position

Let’s write a compare function to sort numbers.

function compare(a, b) {

  if (a < b ) {
    return -1;
  }
	
  if (a > b ) {
    return 1;
  }
	
  // otherwise a == b
  return 0;
	
}

// Now if we execute
 
var array = [2,1,11];
array.sort(compare);

log(array); [1,2,11];

The above compare function can be simplified as:

function compareNumbers(a, b) {

  return a - b;
	
}

Because, when we do a-b, if a > b then it returns number > 0. If a<b, then it returns < 0. When a=b , then it returns 0.

To sort numbers in Descending Order, just change the a-b to b-a .

function Descending(a, b) {

    return b- a; 
		
}

Sorting Array of Objects

var users = [ {name: "John", age:20}, {name:"Antony" , age : 33}];

function sortByAge(obj1, obj2) {

    return obj1.age - obj2.age;
		
}

function sortByName(obj1, obj2) {
   return obj1.name.localeCompare(obj2.name);
} 

users.sort(sortByAge);

// output 
0: {name: "John", age: 20}
1: {name: "Antony", age: 33}

users.sort(sortByName);

//output

0: {name: "Antony", age: 33}
1: {name: "John", age: 20}

The **localeCompare()** method used in sortByName compareFunction returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.

If the CompareFunction returns undefined, null, NaN, Infinity, then the array will not sort two members

var array = [3,2,1, 110, 102 , 30];

function customCompare(a, b){
   if(a > 10 || b > 10) {
      return Infinity;
   }
   else {
      return a-b;
   }
}

array.sort(customCompare);

In the above example, we have defined if the a and b is less than 10 , it will sort by ascending order. Otherwise, the function will return Infinity, though Infinity > 0. But, it will not be swapped. This is the same for undefined, null, NaN.

Thank you for reading !

#JavaScript #Javascript Tips #Data Structures #Programming

What is GEEK

Buddha Community

Sorting Method of Arrays in JavaScript
Terry  Tremblay

Terry Tremblay

1602154740

Fill and Filter in Array in JavaScript

By the word Array methods, I mean the inbuilt array functions, which might be helpful for us in so many ways. So why not just explore and make use of them, to boost our productivity.

Let’s see them together one by one with some amazing examples.

Array.fill():

The _fill()_ method changes all elements in an array to a static value, from a start index (default _0_) to an end index (default _array.length_). It returns the modified array.

In simple words, it’s gonna fill the elements of the array with whatever sets of params, you pass in it. Mostly we pass three params, each param stands with some meaning. The first param value: what value you want to fill, second value: start range of index(inclusive), and third value: end range of index(exclusive). Imagine you are going to apply this method on some date, so that how its gonna look like eg: array.fill(‘Some date’, start date, end date).

NOTE: Start range is inclusive and end range is exclusive.

Let’s understand this in the below example-

//declare array
var testArray = [2,4,6,8,10,12,14];

console.log(testArray.fill("A"));

When you run this code, you gonna see all the elements of testArray will be replaced by 'A' like [“A”,"A","A","A","A","A","A"].

#javascript-tips #array-methods #javascript-development #javascript #arrays

Lowa Alice

Lowa Alice

1624388400

JavaScript Arrays Tutorial. DO NOT MISS!!!

Learn JavaScript Arrays

📺 The video in this post was made by Programming with Mosh
The origin of the article: https://www.youtube.com/watch?v=oigfaZ5ApsM&list=PLTjRvDozrdlxEIuOBZkMAK5uiqp8rHUax&index=4
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#arrays #javascript #javascript arrays #javascript arrays tutorial

Tanya  Shields

Tanya Shields

1594911120

Learn Arrays And Array Methods in JavaScript

In JavaScript, an array is a data structure that contains list of elements which store multiple values in a single variable. The strength of JavaScript arrays lies in the array methods. Array methods are functions built-in to JavaScript that we can apply to our arrays — Each method has a unique function that performs a change or calculation to our array and saves us from writing common functions from scratch.
In this video we are going to learn arrays and array methods like sort(), reverse(), join(), split(), pop(), push(), shift(), unshift(), toString(), delete array, etc…

#javascript #arrays #array methods #programming

Javascript Array Sort Example | JS Array sort() Method

Javascript array sort() is the inbuilt method that sorts all the items of the array in place and returns that array. The sort() method can also accept the parameter like function. So it will sort an array based on that function logic. The default sort order is built on converting the item into strings and then comparing their sequences of UTF-16 code unit values.

Javascript array sort example

The sort order can be either an alphabetic or the numeric, and either the ascending (up) or descending (down). Javascript array sort() method is not a pure function because the sort() method changes the original array.

Syntax

array.sort(compareFunction)

The compareFunction_() _parameter is an optional argument. The function that defines an alternative sort order and it should return a negative, zero, or positive value, depending on the arguments.

#javascript #js array sort

Madilyn  Kihn

Madilyn Kihn

1590478483

Convert String To Array Using Javascript Split Method

The easiest approach to use javascript built-in method String.split().

#javascript #javascript string #string to array #morioh #array