Home > Java > javaTutorial > How to convert and sort arrays in Javascript?

How to convert and sort arrays in Javascript?

青灯夜游
Release: 2018-09-15 16:05:17
Original
1553 people have browsed it

This chapter will introduce you to how to perform array conversion and sorting in Javascript, so that you can understand the methods of array conversion and sorting in Javascript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Array conversion

In our project development process, conversion between data types plays a very important role, and array conversion Into other data types is a common one for us.

toString

This method converts the array into a string. Each element of the array will call the "toString" method and return a new string. The string is concatenated in the form of a string of each element in the array, and the elements are separated by commas.

I don’t understand the definition. Let’s look at an example and we will understand it immediately!

//语法
array.toString()
Copy after login

Case 1

const numbers = [1, 2, 3, 4, 5];
const result = numbers.toString();
console.log(result); //1,2,3,4,5
console.log(typeof  result); //string
Copy after login

Case 2

const numbers = ["A", "B", "C"];
const result = numbers.toString();
console.log(result); //A,B,C
console.log(typeof  result); //string
Copy after login
//利用 reduce 方法模拟 toString 的执行过程
const numbers = [1, 2, 3, 4, 5];
const result = numbers.reduce((prev, current) => {
    return  prev.toString() + "," + current.toString();
});
console.log(result); //1,2,3,4,5
Copy after login

Some people may have questions after seeing this, can they only be separated by commas? Is it possible if I separate them with other characters? I can tell you that the "toString" method will definitely not work, but we can use other methods.

Old rules, we will still look at compatibility at the end of each method.

How to convert and sort arrays in Javascript?

join

This method also converts an array into a string and returns a new character string. The

method will convert each element of the array into a string, and then use the given characters to splice it into a new string and return it to us.

This method accepts one parameter: the separator we gave.

//语法
array.join(separator)
Copy after login

Although the syntax seems relatively simple, there are a few points we need to pay attention to.

The parameters are optional. If there are no parameters, the default is a comma (,)

Parameters It can be an empty string (""), in which case a string without any character delimiters will be returned.

If there is undefined or null in the elements of the array, it will be converted into an empty string ("")

The parameters can be spaces, and the elements will be separated by spaces

const numbers = [1, 2, 3, 4, 5];
const result1 = numbers.join();
console.log(result1);//1,2,3,4,5
const result2 = numbers.join("");
console.log(result2);//12345
const result3 = numbers.join(" ");
console.log(result3);//1 2 3 4 5
const result4 = numbers.join("-");
console.log(result4);//1-2-3-4-5
const result5 = numbers.join("A");
console.log(result5);//1A2A3A4A5
Copy after login

What is the compatibility of the "sort" method? Directly above the picture.

How to convert and sort arrays in Javascript?

Sorting of arrays

Sorting of arrays is used in many scenarios, such as ascending order of tables Sorting is used in descending order, arranging data from large to small or arranging according to certain rules. How to effectively use data sorting methods, first of all, you must have a certain understanding of these methods before you can use more appropriate methods.

reverse

We should be able to guess the function of this method from the name. This method is to reverse the order of the elements in the array.

//语法
array.reverse()
Copy after login
//案例
const numbers = [1, 2, 3, 4, 5];
numbers.reverse();
console.log(numbers); //[5, 4, 3, 2, 1]
Copy after login

The method is relatively simple, and there is nothing to explain, but there are relatively few application scenarios. In actual projects, we do not have such simple data structures and simple sorting rules. Let’s focus on one. A very cool and flexible sorting method.

Compatibility of "reverse" method.

How to convert and sort arrays in Javascript?

sort

This method sorts the elements of the array, in ascending order by default. Let's take a look at two examples first

//案例1
const numbers = [1, 3, 5, 2, 4];
numbers.sort();
console.log(numbers); //[1, 2, 3, 4, 5]
Copy after login
//案例2
const numbers2 = [1, 15, 20, 2, 3];
numbers2.sort();
console.log(numbers2);//[1, 15, 2, 20, 3]
Copy after login

You will find that the sorting rules are not what we thought, what is going on?
In fact, when the "sort" method is executed, each element of the array will first execute the toString() method once, and then sort according to the Unicode encoding of the string.

So how can we sort according to our own wishes or rules?

其实「sort」方法还接受一个可选的参数:该参数是一个函数,它可以用来指定我们数组排序的规则。

//语法
array.sort([callback])
Copy after login

那么我们应该如何利用这个参数去指定我们排序的规则呢?参数函数接受两个参数,然后会根据返回的两个参数的比较值进行排序。

array.sort(compare(a, b){
    return a- b
});
Copy after login

排序的规则如下:

  • 如果 a - b 小于 0 ,那么 a 在 b 的前面,也就是会按照升序排列

  • 如果 a - b 等于 0 ,那么 a 和 b 的位置相对不变

  • 如果 a - b 大于 0 ,那么 b 在 a 的前面,也就是会按照降序排列。

例如我们想把上面的案例2中的数组按照数字的大小进行排列,我们只需要加入上面我们说的比较函数

const numbers2 = [1, 15, 20, 2, 3];
numbers2.sort(function(a ,b){
    return a- b;
});
console.log(numbers2);//[1, 2, 3, 15, 20]
Copy after login

是不是 so easy!如果我们想要进行降序排列也很简单,调换一个我们的计算方法就行。

const numbers2 = [1, 15, 20, 2, 3];
numbers2.sort(function(a ,b){
    return b - a;
});
console.log(numbers2);//[20, 15, 3, 2, 1]
Copy after login

但是在实际的使用当中我们不仅仅比较的是数字与字符类型,也可以能是比较的是对象,不过没关系我们依旧可以使用对象的属性去进行排序。

const friends = [{
    name: "大B哥",
    age: 25
}, {
    name: "二B哥",
    age: 30
}, {
    name: "三B哥",
    age: 28
}, {
    name: "我",
    age: 14
}];
friends.sort(function(a, b){
    return b.age - a.age;
});
console.log(friends);
Copy after login
//排序之后
//[{name: "二B哥", age: 30},
//{name: "三B哥", age: 28},
//{name: "大B哥", age: 25},
//{name: "我", age: 14}]
Copy after login

可以看到我交的朋友一般都比较偏大,一眼就能看出哪个是最大的,哪个是最小的,不过我相信大家也看出来了,最小的哪个就是我(… 哈哈)。

至于 sort 更多更有趣的方法,小伙伴们不妨自己去寻找尝试吧。

继续来看看「sort」方法的兼容性。

How to convert and sort arrays in Javascript?

The above is the detailed content of How to convert and sort arrays in Javascript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template