How to find and sort arrays

Source: Internet
Author: User

How to sort arrays:
Reverse () Reverses the order of the array elements.
Sort () Sorts the elements of an array. You can not write, or you can pass a custom function to sort.

var = [2, 14, 3, 37, 5, 40];
Console.log (. sort ()); [14, 2, 3, 37, 40, 5]
Console.log (. reverse ()); [5, 40, 37, 3, 2, 14]

var = [5, 21, 19, 8, 3];
function Sortfn (A, b) {
return a> B;
}
Console.sort (SORTFN);
Console.log (arr); [3, 5, 8, 19, 21]

Arrow functions:
var = [5, 21, 19, 8, 3];
Arr.sort ((a, b) = a> B);
Console.log (arr); [3, 5, 8, 19, 21]

Summarize:
Return values a > B, which are arranged in small to large order.
Return values a < B, arrays are arranged in order from large to small.

Connection method:
Concat () joins two or more arrays and returns the result. Array names or array elements that need to be merged

var = ["Red", "Blue", "green"];
var =. Concat ("Yellow", ["Black", "pink"]);
Console.log ();//Red,blue,green,yellow,black,pink

Location Method:
IndexOf () finds the specified element starting at the head of the array, returning the index value of the element in the array.
LastIndexOf () returns the index value of the element in the array, starting at the end of the array and looking forward to the specified element.

var = ["A", "B", "C", "D", "E", "C"];
Console.log (arr. indexOf ("C")); 2
Console.log (Arr.lastindexof ("C")); 5

Note: If the found element does not exist in the array, 1 is returned.

How to find and sort arrays

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.