definitionThe reduce() method executes a reducer function that you provide for each element in the array (in ascending order), summarizing the results into a single return value. reduce(), like forEach(), map(), and filter(), also traverses each item in the array, but reduce() can operate on the result of the previous traversed array item with the current traversed item. grammararray.reduce(function(prev, cur, index, array){ ... }, init); Parameters in the callback function:
Common parameters: prev and cur Note: When the callback function is executed for the first time, there are two cases for the values of prev and cur: if the initial value init is provided when reduce() is called, prev takes the init value and cur takes the first value in the array, and the index starts from 0; if the initial value init is not provided, prev takes the first value in the array and cur takes the second value in the array, and the index starts from 1. Examples1. No initial value init is passedconst arr = [1, 3, 5, 7] arr.reduce(function(prev, cur, index, arr){ console.log(prev, cur, index) return prev + cur }) The parameters and return values for each call are as follows:
Because no initial value is passed in, the index starts at 1. The callback is called three times. At the beginning, the value of prev is 1, the first item in the array, and the value of cur is 3. After adding them together, the return value 4 is used as the prev value of the next round of callbacks. Then the next round of callbacks is continued until it is completed and returned. 2. When passing initial valueconst arr = [1, 3, 5, 7] arr.reduce(function(prev, cur, index, arr){ console.log(prev, cur, index) return prev + cur }, 10) The parameters and return values for each call are as follows:
3. Array deduplicationconst arr = ['ab', 'v', 'd', 'ab', 'h', 'e', 'dc', 'e', 'e', 'f'] const newArr = arr.reduce(function(prev, cur){ !prev.includes(cur) && prev.push(cur) return prev }, []) console.log(newArr) // ["ab", "v", "d", "h", "e", "dc", "f"] The steps to perform are as follows:
4. Use reduce to group and merge Object objects in an array//Get the object array from the background, group it according to the object type and merge it into a tree to display the data const dataArr = [ { type: 'Governance layer', name: 'hive_82', reserve: '2', id: 1 }, { type: 'Original data layer', name: 'qwe', reserve: '1', id: 2 }, { type: 'Source layer', name: 'mysql_exchangis', reserve: '3', id: 3 }, { type: 'Governance layer', name: 'links_188', reserve: '1', id: 4 }, { type: 'Source layer', name: 'mysql_ces', reserve: '2', id: 5 } ] const treeData = dataArr.reduce((cur, next) => { const obj = cur.find(curItem => curItem.label === next.type) if (obj) { if (obj.children.indexOf(next.id) === -1) { //de-duplication obj.children.push({ ...next, label: next.name }) } } else { const newObj = { label: next.type, children: [{ ...next, label: next.name }] } cur.push(newObj) } return cur }, []) // The result after merging: treeData = [ { label: 'Governance', children: [ { type: 'Governance layer', name: 'hive_82', reserve: '2', id: 1, label: 'hive_82' }, { type: 'Governance layer', name: 'links_188', reserve: '1', id: 4, label: 'links_188' } ] }, { label: 'Original data layer', children: [ { type: 'Original data layer', name: 'qwe', reserve: '1', id: 2, label: 'qwe' } ] }, { label: 'Source layer', children: [ { type: 'Source layer', name: 'mysql_exchangis', reserve: '3', id: 3, label: 'mysql_exchangis' }, { type: 'Governance layer', name: 'mysql_ces', reserve: '2', id: 5, label: 'mysql_ces' } ] } ] 5. Use reduce to process the menu structure returned by the menu backendThis data needs to be converted into a hierarchical structure based on parentId. Method 1: const dataArr = [ {id: '18', name: 'Reset Password', parentId: '30', parentName: 'User Management'}, {id: '13', name: 'Audit Log', parentId: '29', parentName: 'System Management'}, {id: '29', name: 'System Management', parentId: '0', parentName: null}, {id: '14', name: 'Modify', parentId: '33', parentName: 'Department Management'}, {id: '2', name: 'User List', parentId: '30', parentName: 'User Management'}, {id: '30', name: 'User Management', parentId: '29', parentName: 'System Management'}, {id: '33', name: 'Department Management', parentId: '0', parentName: null}, {id: '37', name: 'Add User', parentId: '30', parentName: 'User Management'}, {id: '6', name: 'Add', parentId: '33', parentName: 'Department Management'}, {id: '7',name: 'Delete', parentId: '33', parentName: 'Department Management'} ] //Create a mapping relationship for menu id const idMapping = dataArr.reduce((prev, next, i) => { prev[next.id] = i return prev }, {}) const treeData = [] dataArr.map(el => { // First level menuif (el.parentId === '0') { treeData.push(el) return } // Find the parent element through mapping const parentEl = dataArr[idMapping[el.parentId]] // Add the current element to the `children` array of the parent element parentEl.children = [...(parentEl.children || []), el] }) console.log(treeData) Method 2: //Create a mapping relationship based on parentId const result = dataArr.reduce((prev, next) => { prev[next.parentId] ? prev[next.parentId].push(next) : prev[next.parentId] = [next]; return prev; }, {}); Object.keys(result).map(key => { result[key].map((item, i) => { result[item.id] ? item.children = result[item.id] : '' }); }) this.treeData = result[0] console.log(treeData) It can also be achieved through recursion, which will not be described in detail. The final data structure is shown in the figure below: The above is the details of how JS uses the reduce() method to process tree structure data. For more information about JS, please pay attention to other related articles on 123WORDPRESS.COM! You may also be interested in:
|
<<: Example of how to optimize MySQL insert performance
When using XAML layout, sometimes in order to make...
1. display:box; Setting this property on an eleme...
Three ways to introduce CSS 1. Inline styles Adva...
Table of contents 1. Count data is lost Solution ...
This article uses an example to describe how to u...
Copy code The code is as follows: @charset "...
What to do if you forget Windows Server 2008R2 So...
NextCloud You can share any files or folders on y...
Preface During the development process, we often ...
How to determine whether the current Linux system...
Preface Recently, during an interview, I was aske...
Table of contents File() grammar parameter Exampl...
The excellence of Linux lies in its multi-user, m...
1. Basic structure: Copy code The code is as follo...
This article shares the installation steps of MyS...