JS uses the reduce() method to process tree structure data

JS uses the reduce() method to process tree structure data

definition

The 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.

grammar

array.reduce(function(prev, cur, index, array){
    ...
}, init);

Parameters in the callback function:

  • prev Required. Indicates the return value when the callback is called, or the initial value init.
  • cur Required. Represents the current element.
  • index Optional. Indicates the index of the current element.
  • array represents the original array.
  • init Optional. The initial value, used as the first argument of the first call to 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.

Examples

1. No initial value init is passed

const 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:

callback prev cur index array return value
1st time 1 3 1 [1, 3, 5, 7] 4
2nd time 4 5 2 [1, 3, 5, 7] 9
3rd 9 7 3 [1, 3, 5, 7] 16

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 value

const 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:

callback prev cur index array return value
1st time 10 1 0 [1, 3, 5, 7] 11
2nd time 11 3 1 [1, 3, 5, 7] 14
3rd 14 5 2 [1, 3, 5, 7] 19
4th 19 7 3 [1, 3, 5, 7] 26

3. Array deduplication

const 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:

  • Initialize an empty array
  • When called for the first time, prev is the initial value, that is, an empty array, and cur is the first item in the array, arr[1]. Then, it searches prev to see if cur already exists. If not, it adds the item to prev, and prev returns to enter the next callback.
  • In the second callback, prev is the return value of the first callback, cur is the second item in the array arr[2], and then it searches prev to see if cur already exists. If not, it adds the item to prev, and prev returns to enter the next callback.
  • Finally, return the prev array

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 backend

This 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:
  • JavaScript data structure: creation of hash table (1)
  • JavaScript data structure dictionary method
  • JavaScript data structure collection creation (2)
  • JavaScript data structure collection creation (1)
  • Detailed explanation of Map data structure in JavaScript
  • Convert Go language data structure to JSON
  • JavaScript efficient algorithm for converting flat data into tree structure
  • js realizes infinite hierarchical tree data structure (innovative algorithm)
  • JavaScript data structure: creation of hash table (2)

<<:  Example of how to optimize MySQL insert performance

>>:  Detailed explanation of the reasons and optimizations for the large offset affecting performance during MySQL query

Recommend

WeChat applet custom scroll-view example code

Mini Program Custom Scroll-View Scroll Bar Withou...

Linux CentOS6.9 installation graphic tutorial under VMware

As a technical novice, I am recording the process...

MySQL 8.0.12 installation graphic tutorial

MySQL8.0.12 installation tutorial, share with eve...

How to install MySQL using yum on Centos7 and achieve remote connection

Centos7 uses yum to install MySQL and how to achi...

Tools to convert static websites into RSS

<br /> This article is translated from allwe...

How to implement Mysql switching data storage directory

How to implement Mysql switching data storage dir...

Implementation of react automatic construction routing

Table of contents sequence 1. Centralized routing...

JavaScript implementation of the Game of Life

Table of contents Concept Introduction Logical ru...

Analysis of the principles and usage of Linux hard links and soft links

In the Linux system, there is a kind of file call...

Implementation steps for installing RocketMQ in docker

Table of contents 1. Retrieve the image 2. Create...

Application of CSS3 animation effects in activity pages

background Before we know it, a busy year is comi...

HTML code text box limit input text box becomes gray limit text box input

Method 1: Set the readonly attribute to true. INPU...

Basic Implementation of AOP Programming in JavaScript

Introduction to AOP The main function of AOP (Asp...