ES6 array sorting: more recommended methods and techniques than Es5


Original link: HTTPS: / / dsx2016. COM /? P = 692

WeChat official account: Senior brother 2016


ECMA ScriptyesECMA-262The name of the standardized scripting language.

althoughJavaScriptandJScriptAndECMAScriptCompatible, but contains more thanECMA ScriptFunction.

The following table is divided into four modules:

  • ECMAScript 1st Edition (ECMA-262)Corresponding to the first edition andES5Previous versions (this article only)
  • ECMAScript 5.1 (ECMA-262)CorrespondingES5
  • ECMAScript 2015 (6th Edition, ECMA-262)CorrespondingES6
  • ECMAScript LasterCorrespondingES7/ES8/ES9/ES10etc.

Because of the length, asmap(), and so on

ES 1st ES5 ES6 ES Laster
Array.length Array.isArray() Array.from() includes()
unshift() indexOf() Array.of()
concat() lastIndexOf() findIndex()
join() every() find()
pop() some() fill()
push() forEach() copyWithin()
reverse() map() entries()
shift() filter() flat()
slice() reduce() flatMap()
sort() reduceRight() includes()
splice() keys()
toLocaleString() values()

Remove duplicates from array

ES6There are two ways to use theSetData structure to remove duplicate values

let fruits=[`banana`,`orange`,`apple`,`pear`,`grape`,`apple`];

The first way, usingArray.from()

let deduplicationFruits=Array.from(new Set(fruits))

The second way, using...Extended operator(recommended)

let deduplicationFruits=[ Set(fruits)]

Determine whether there is a given value in the array


let arr=[1,2,NaN]
if (arr.indexOf(1) !== -1) {
  // ...
// attention
[NaN].indexOf(NaN) // -1

ES6UseArray.prototype.includes() (recommended)

let arr=[1,2,NaN]
arr.includes(1) // true
[NaN].includes(NaN) // true

Check whether it is an array

ES5UseArray.isArray() (recommended), other methods will not be described

const arr = [];
const obj = {};

Shallow copy and deep copy

Shallow copy

ES6Use...Extended operator

Note: this method is a shallow copy

let arr1=[1,2,3,{a:123}];
let arr2=[...arr1] 
arr2[0]=5 // arr1[1,2,3,{a:123}] arr2[5,2,3,{a:123}];
arr2[3].a=456 // arr1[1,2,3,{a:456}] arr2[5,2,3,{a:456}];

Deep copy

UseJSONSerializationJSON.parse(JSON.stringify(arr))This method is simple and can satisfy the general scene

This method is not compatible with complex properties of objects, such asset,get,FunctionWait, compatible onlyJSONData types supported by format

For regular expression type, function type, etc., deep copy is not allowed, and corresponding values will be lost directly

let arr1=[1,2,3,{a:123}]
let arr2=JSON.parse(JSON.stringify(arr1))

Recommended Today

PHP Basics – String Array Operations

In our daily work, we often need to deal with some strings or arrays. Today, we have time to sort them out String operation <?php //String truncation $str = ‘Hello World!’ Substr ($STR, 0,5); // return ‘hello’ //Chinese string truncation $STR = ‘Hello, Shenzhen’; $result = mb_ Substr ($STR, 0,2); // Hello //First occurrence of […]