What is an expand operator? What is its function?
Expand operators can expand an array
const arr = [1,2,3,4,5] // We use... to expand the array (...arr) //1 2 3 4 5
It will not modify the original array
Typical application scenarios: find the maximum value, minimum value, merge array, etc.It will make our code more concise
Maximum value
const arr = [1,2,3,4,5] //...arr is equivalent to 1,2,3,4,5 ((...arr)) // 5
Minimum value
const arr = [1,2,3,4,5] //...arr is equivalent to 1,2,3,4,5 ((...arr)) // 1
merge
const arr1 = [1,2,3] const arr2 = [4,5,6] const arr = [...arr1,...arr2] (arr) //[1, 2, 3, 4, 5, 6]
Attachment: js array expansion object deduplication
In JavaScript, array expansion operators and Set data structures can be used to deduplicate array expansion objects. Here are the steps to implement:
- Define an array containing duplicate objects.
- Use the array expansion operator to expand the array into a new array.
- Use the Set data structure to remove duplicates in the array.
- Convert Set back to array.
Here is a code example:
let arr = [ {id: 1, name: 'Zhang San'}, {id: 2, name: 'Li Si'}, {id: 1, name: 'Zhang San'}, {id: 3, name: 'Wang Wu'} ]; let uniqueArr = [...new Set([...arr])]; (uniqueArr); // Output: [{id: 1, name: 'Zhang San'}, {id: 2, name: 'Li Si'}, {id: 3, name: 'Wang Wu'}]
In the above code, we use the array expansion operator to expand the original array into a new array. We then use the Set data structure to remove duplicates in the array. Finally, we convert Set back to the array and assign the result touniqueArr
variable. final,uniqueArr
The array of objects will be included after deduplication.
Summarize
This is the end of this article about JavaScript array expansion operators. For more related JS array expansion operator content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!