In the recent project, we encountered a scene of more processing arrays, such as extracting and classifying a field of an element in the array, or judging whether an element in the array meets the judging conditions, etc.
There are a lot of articles on the Internet about using ES5 new API to replace for loop. Some of them discuss the usage of API in detail, some analyze their performance in detail, and some sort out the matters needing attention in use. Therefore, this article will not repeat the detailed usage of these API, only from a personal point of view, sort out and summarize some examples that can handle array traversal more gracefully in project practice.
1. UseSet
Handle the problem of array deduplication and element elimination
Set
Is a new addition to es6Data structure, which is very similar to arrays, but the values of members are unique and there are no duplicate values. It provides four semantic API:
add(value)
: Adds a value and returns the Set structure itself.
delete(value)
: Deletes a value and returns a Boolean value indicating whether the deletion was successful.
has(value)
: Returns a Boolean value indicating whether the value is a member of Set.
clear()
: Clear all members, no return value.Reference from @ Ruan YifengECMAScript 6 Getting Started
Then we can use itSet
What are you doing here?
The first usage, array de-duplication. For a one-dimensional array, we can first convert it intoSet
, and then cooperate with...
Deconstruction operators are converted into arrays again to achieve the goal of de-duplication. Please look at the example:
const arr = [1, 1, 2, 2, 3, 4, 5, 5]
const newArr = [...new Set(arr)]
console.log(newArr)
// [1, 2, 3, 4, 5]
It is worth noting that this method does not work for arrays with “objects” as elements:
const arr = [{ name: 'Alice', age: 12 }, { name: 'Alice', age: 12 }, { name: 'Bob', age: 13 }]
const newArr = [...new Set(arr)]
console.log(newArr)
// [{ name: 'Alice', age: 12 }, { name: 'Alice', age: 12 }, { name: 'Bob', age: 13 }]
This is becauseSet
The way to determine whether an element is duplicated is similar to===
Operator, two objects are always not equal.
In addition to weight removal,Set
Provideddelete()
The method is also very practical. In the past, if we want to delete the specified element in the array, we need to get the subscript of the element first, and then pass through thesplice()
Methods to delete the elements corresponding to subscripts, easy to cause confusion in understanding:
//I want to delete the element with a value of 2 from the array
const arr = [1, 2, 3]
const index = arr.indexOf(2)
if (index ! == -1) {
arr.splice(index, 1)
}
console.log(arr)
// [1, 3]
UseSet
It is much clearer:
const arr = [1, 2, 3]
const set = new Set(arr)
set.delete(2)
arr = [...set]
console.log(arr)
// [1, 3]
2. Usemap()
Methods and Object Deconstruction Syntax Extract Fields
The following data format is likely to be encountered in the data returned by the requesting background interface:
studentInfo = [
{ name: 'Alice', age: 18, no: 2 },
{ name: 'Bob', age: 16, no: 5 },
{ name: 'Candy', age: 17, no: 3 },
{ name: 'Den', age: 18, no: 4 },
{ name: 'Eve', age: 16, no: 1 },
]
When we want to get the name list, the age list and the numbered list, we canmap()
In combination with the deconstruction grammar of the object, it can be conveniently and quickly processed:
const nameList = studentInfo.map(({ name }) => name)
const ageList = studentInfo.map(({ age }) => age)
const noList = studentInfo.map(({ no }) => no)
// nameList: [ 'Alice', 'Bob', 'Candy', 'Den', 'Eve' ]
// ageList: [ 18, 16, 17, 18, 16 ]
// noList: [ 2, 5, 3, 4, 1 ]
3. Usefilter()
Methods and Object Deconstruction Syntax Filter Arrays
Following the above example, what should I do if I want to get a new list of “17 years old or younger”? Similarmap()
Methods, we can usefilter()
Methods Filter:
const newStudentInfo = studentInfo.filter(({ age }) => {
return age <= 17
})
/*
newStudentInfo: [
{ name: 'Bob', age: 16, no: 5 },
{ name: 'Candy', age: 17, no: 3 },
{ name: 'Eve', age: 16, no: 1 }
]
*/
4, with the help ofincludes()
Method to find the difference set of two arrays
Suppose we have the following two arrays:
var a = [1, 2, {s:3}, {s:4}, {s:5}]
var b = [{s:2}, {s:3}, {s:4}, 'a']
How should we find their difference sets? Traditional methods may need to hash them in the form of Object, but in fact we can pass.includes()
The method is more elegant and convenient to find the travel set. The code is as follows:
var a = [1, 2, {s:3}, {s:4}, {s:5}].map(item => JSON.stringify(item))
var b = [{s:2}, {s:3}, {s:4}, 'a'].map(item => JSON.stringify(item))
var diff = a.concat(b)
.filter(v => ! a.includes(v) || ! b.includes(v))
.map(item => JSON.parse(item))
// diff: [1, 2, {s:5}, {s:2}, "a"]
As for whyJSON.stringify()
, because to compare whether two “object elements” are equal, it cannot be directly compared in the form of “object” (always return unequal).
5. Postscript
This article is short in length and relatively simple in difficulty. The above are some skills found in daily practice, hoping to enlighten readers. If you also have some elegant and fun skills, you may as well share them with me.