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

How to convert and sort arrays in Javascript?

Sep 15, 2018 pm 04:05 PM
javascript Array sort Array conversion

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Fast array sorting method that preserves key names in PHP Fast array sorting method that preserves key names in PHP May 02, 2024 pm 03:06 PM

Fast array sorting method in PHP that preserves key names: Use the ksort() function to sort the keys. Use the uasort() function to sort using a user-defined comparison function. Practical case: To sort an array of user IDs and scores by score while retaining the user ID, you can use the uasort() function and a custom comparison function.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JS array sorting: in-depth analysis of the working principle and mechanism of the sort() method JS array sorting: in-depth analysis of the working principle and mechanism of the sort() method Dec 28, 2023 am 11:47 AM

To deeply understand JS array sorting: the principles and mechanisms of the sort() method, specific code examples are required. Introduction: Array sorting is one of the very common operations in our daily front-end development work. The array sorting method sort() in JavaScript is one of the most commonly used array sorting methods. However, do you really understand the principles and mechanisms of the sort() method? This article will give you an in-depth understanding of the principles and mechanisms of JS array sorting, and provide specific code examples. 1. Basic usage of sort() method

See all articles