Have you really mastered the 20 common array methods in front-end development?

Article directory


foreword

Arrays must be dealt with in every language, and the importance is self-evident!
The main usage scenarios of arrays in front-end development are:
storing and processing data : an array is an ordered data structure that can be used to store and process multiple related data. In front-end development, we often use arrays to store and process data such as lists, tables, and options.
Loop and traversal : Arrays provide loop and traversal functions, which can easily operate on each element in the array. In front-end development, we often use loops and traversals to process data such as lists, tables, and options.
Data Filtering and Transformation : Arrays provide methods to filter and transform arrays. For example, we can use the filter() method to filter elements in an array, and use the map() method to transform each element in an array.
Data Sorting and Finding : Arrays provide methods to sort and find arrays. For example, we can use the sort() method to sort an array and the indexOf() method to find an element in the array.
So the array method is an essential skill for front-end personnel! Are you still checking once you encounter it! Let's study together!


以下是本篇文章正文内容,讲解各种数组方法

1. Common array methods

1.1 push (add the specified element to the end of the array and return the new array length)

        let name = ['前', '端', '百'];
        const res = name.push('草','阁'); // 想往数组末端添加几个元素,就传入几个参数
        console.log(name); 
        console.log(res); // 返回新的数组长度

insert image description here

1.2 pop (remove the last element from the array and return the value of the element)

        let name = ['前', '端', '百','草','阁'];
        const res = name.pop(); // 返回被删的那个元素 这里是 '阁'
        console.log(name);
        console.log(res);

insert image description here

1.3 shift (remove the first element from the array and return the value of the element)

        let name = ['前', '端', '百','草','阁'];
        const res = name.shift(); // 返回被删的那个元素 这里是 '前'
        console.log(name);
        console.log(res);

insert image description here

1.4 unshift (add one or more elements to the first position of the array and return the new array length)

        let name = [ '百','草','阁'];
        const res = name.unshift('前', '端'); // 向数组开头添加一个或多个元素
        console.log(name);
        console.log(res); // 返回添加后数组的长度

insert image description here

1.5 concat (merge multiple arrays or values, return a new array)

        let name1 = ['前', '端']; // 数组
        let name2 = [ '百','草']; // 数组
        let name3 = '阁'; // 值
        const res = name1.concat(name2,name3); // name1数组 拼接上 name2数组 以及 name3值
        console.log(name1,name2,name3); // 原数组和值都不曾改变
        console.log(res); // 返回一个新数组

insert image description here

1.6 slice (intercept a part of the array and return a new array)

        let name = ['前', '端', '百','草','阁'];
        const res = name.slice(2); // 从第三个元素开始截取直至最后一个元素
        const res2 = name.slice(1,3) // 从第二个开始截取!
到第四个元素 但不包括第四个元素 左闭右开
        console.log(res);
        console.log(res2);

insert image description here
It is worth mentioning that the parameters of slice can be passed in negative numbers, -1 represents the last element, -2 represents the last two elements

        let name = ['前', '端', '百','草','阁'];
        const res = name.slice(-2); // 从倒二个元素开始截取直至最后一个元素
        const res2 = name.slice(0,-1) // 从第一个开始截取到最后一个个元素 但不包括最后一个元素 左闭右开
        console.log(res);
        console.log(res2);

insert image description here

1.7 splice (remove, replace, or add elements of an array, and return the removed elements)

        let name = ['前', '端', '百','草','阁'];
        name.splice(2,0,'你好'); // 从第三个元素开始删,删0个,并且在第三个元素前加上 '你好'
        console.log(name);
        const res = name.splice(0,2,'你','好','呀') // 从第一个元素开始删,删2个,并且添加上两个元素
        console.log(name);
        console.log(res); // 被删除的元素 '前' '端'

insert image description here

1.8 filter (filter the elements in the array, return a new array)

        const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
        const result = words.filter(word => word.length > 6); // 循环筛选出 长度大于6的 并返回一个新的数组
        console.log(result); //  ["exuberant", "destruction", "present"]

1.9 map (operate on each element in the array and return a new array)

        const array1 = [1, 4, 9, 16];
        const map1 = array1.map(item => item * 2); // 循环进行一个每一项都乘以2的操作 并返回一个 新数组
        console.log(map1); // [2, 8, 18, 32]

1.10 sort (to sort an array)

        const arr = [1000,10,1,4,3,2,77]
        const arr2 = [1000,10,1,4,3,2,77]
        arr.sort((x,y) => x - y) // 正序
        console.log(arr); //  [1, 2, 3, 4, 10, 77, 1000]
        arr2.sort((x,y) => y - x) // 倒序
        console.log(arr2); // [1000, 77, 10, 4, 3, 2, 1]

1.11 reverse (reverse the elements in the array)

        const arr = [1,2,3,4,5]
        arr.reverse()
        console.log(arr); //  [5, 4, 3, 2, 1]

1.12 indexOf (find the index of the specified element in the array)

        const arr = [1,2,3,4,5,3]
        const num = arr.indexOf(3) // 查找 3 出现的索引 只能查找到首次出现的索引
        console.log(num); // 2 
        const num1 = arr.indexOf(6) // 查找 6 出现的索引 找不到为-1
        console.log(num1); // -1

1.13 find (find the first element in the array that meets the conditions)

        const array1 = [5, 12, 8, 130, 44];
        const found = array1.find(item => item > 10); // 找到第一个大于10的元素
        console.log(found); // 12

1.14 findIndex (find the index of the first element in the array that meets the criteria)

        const array1 = [5, 12, 8, 130, 44];
        const found = array1.findIndex(item => item > 10); // 找到第一个大于10的元素的索引
        console.log(found); // 1

1.15 includes (judging whether an array contains a specified value)

        const pets = ['cat', 'dog', 'bat'];
        const res = pets.includes('cat') // 数组里是否包含 'cat' 是的话返回true 不是的话返回false
		console.log(res); // true		

1.16 every (judging whether all elements in the array can pass the test of the specified function)

        const array1 = [1, 30, 39, 29, 10, 13];
        const res = array1.every(item => item > 0) // 判断数组中每一个元素是否都大于0
        console.log(res); // true
        const res2 = array1.every(item => item > 30) // 判断数组中每一个元素是否都大于30
        console.log(res2); // false

1.17 some (judging whether at least one element in the array has passed the test of the specified function)

        const array1 = [1, 30, 39, 29, 10, 13];
        const res = array1.some(item => item > 10) // 判断数组中是否至少有一个元素大于10
        console.log(res); // true
        const res2 = array1.some(item => item > 100) // 判断数组中是否至少有一个元素大于100
        console.log(res2); // false

1.18 join (connect all elements of an array into a string and return this string)

        const elements = ['Fire', 'Air', 'Water'];

        const res = elements.join() // 将数组中每一个元素用逗号连接
        console.log(res); // Fire,Air,Water

        const res1 = elements.join('-') // 将数组中每一个元素用-连接
        console.log(res1); // Fire-Air-Water
        
        const res2 = elements.join('') // 将数组中每一个元素用''连接
        console.log(res2); // FireAirWater

1.19 reduce (calculate the sum of all elements of the array)

        const array1 = [1, 2, 3, 4];
        const initialValue = 0; 
        // 0+1+2+3+4
        const sumWithInitial = array1.reduce((accumulator, currentValue) => accumulator + currentValue,initialValue);
         // initialValue 是初始值
        console.log(sumWithInitial); // 10

1.20 forEach (array loop traversal)

		const array1 = ['a', 'b', 'c'];
		array1.forEach(element => console.log(element)); 
		// a
		// b
		// b

2. Convert the tiled array structure to a tree-type array structure

Here we first give the tiled array structure , where pid is his father and id is himself

[
            {
    
    
                "id": "604e21feb205b95968e13129",
                "pid": "",
                "name": "总裁办",
                "code": "1001",
                "manager": "管理员",
                "introduce": "公司战略部",
                "createTime": "2021-03-14 22:47:25"
            },
            {
    
    
                "id": "604e222bb205b95968e1312a",
                "pid": "",
                "name": "行政部",
                "code": "XZB",
                "manager": "管理员",
                "introduce": "行政部",
                "createTime": "2021-03-14 22:47:25"
            },
            {
    
    
                "id": "604e223fb205b95968e1312b",
                "pid": "",
                "name": "人事部",
                "code": "RSB",
                "manager": "管理员",
                "introduce": "人事部",
                "createTime": "2021-03-14 22:47:25"
            },
            {
    
    
                "id": "604e2251b205b95968e1312c",
                "pid": "",
                "name": "财务部",
                "code": "CWB",
                "manager": "管理员",
                "introduce": "财务部",
                "createTime": "2021-03-14 22:47:25"
            },
            {
    
    
                "id": "604e2262b205b95968e1312d",
                "pid": "604e2251b205b95968e1312c",
                "name": "财务核算部",
                "code": "CWHSB",
                "manager": "管理员",
                "introduce": "财务核算部",
                "createTime": "2021-03-14 22:47:25"
            },
            {
    
    
                "id": "604e227db205b95968e1312e",
                "pid": "604e2251b205b95968e1312c",
                "name": "税务管理部",
                "code": "SWGLN",
                "manager": "管理员",
                "introduce": "税务管理部",
                "createTime": "2021-03-14 22:47:25"
            },
            {
    
    
                "id": "604e2297b205b95968e1312f",
                "pid": "604e2251b205b95968e1312c",
                "name": "薪资管理部",
                "code": "XZGLB",
                "manager": "管理员",
                "introduce": "薪资管理部",
                "createTime": "2021-03-14 22:47:25"
            },
            {
    
    
                "id": "6051ad90e93db6522c1d00d2",
                "pid": "",
                "name": "技术部",
                "code": "JSB",
                "manager": "孙财",
                "introduce": "技术部",
                "createTime": "2021-03-17 15:18:23"
            },
            {
    
    
                "id": "6051adb6e93db6522c1d00d3",
                "pid": "6051ad90e93db6522c1d00d2",
                "name": "Java研发部",
                "code": "JYFB",
                "manager": "管理员",
                "introduce": "JAVA研发部",
                "createTime": "2021-03-17 15:18:23"
            },
            {
    
    
                "id": "6051add6e93db6522c1d00d4",
                "pid": "6051ad90e93db6522c1d00d2",
                "name": "Python研发部",
                "code": "PYFB",
                "manager": "罗晓晓",
                "introduce": "Python研发部",
                "createTime": "2021-03-17 15:18:23"
            },
            {
    
    
                "id": "6051adefe93db6522c1d00d5",
                "pid": "6051ad90e93db6522c1d00d2",
                "name": "Php研发部",
                "code": "PhpYFB",
                "manager": "孙财",
                "introduce": "Php研发部",
                "createTime": "2021-03-17 15:18:23"
            },
            {
    
    
                "id": "6051ae03e93db6522c1d00d6",
                "pid": "",
                "name": "运营部",
                "code": "YYB",
                "manager": "孙财",
                "introduce": "运营部",
                "createTime": "2021-03-17 15:18:23"
            },
            {
    
    
                "id": "6051ae15e93db6522c1d00d7",
                "pid": "",
                "name": "市场部",
                "code": "SCB",
                "manager": "孙财",
                "introduce": "市场部",
                "createTime": "2021-03-17 15:18:23"
            },
            {
    
    
                "id": "6051ae28e93db6522c1d00d8",
                "pid": "6051ae15e93db6522c1d00d7",
                "name": "北京事业部",
                "code": "BJSYB",
                "manager": "孙财",
                "introduce": "BJSYB",
                "createTime": "2021-03-17 15:18:23"
            },
            {
    
    
                "id": "6051ae3de93db6522c1d00d9",
                "pid": "6051ae15e93db6522c1d00d7",
                "name": "上海事业部",
                "code": "SHSYB",
                "manager": "文吉星",
                "introduce": "上海事业部",
                "createTime": "2021-03-17 15:18:23"
            }
        ]

Convert a tile structure to a tree structure

function tranListToTreeData(list) {
    
    
  // 定义两个变量 一个用来解决映射关系 更快速的匹配到id对应的数据
  const map = {
    
    }
  // 存放最后生成的树形数组
  const treeList = []
  // 目前数组还是平铺状态,先做好映射关系
  list.forEach(item => {
    
    
    // 这样map这个对象里面的键值对 就是id和数据的对应关系
    map[item.id] = item
  })
  list.forEach(item => {
    
    
    // 无论是item 还是parent 都是一个对象 涉及浅拷贝 拿的都是地址
    const parent = map[item.pid]
    if (parent) {
    
    
      if (!parent.children) {
    
    
        parent.children = []
      }
      parent.children.push(item)
    } else {
    
    
      treeList.push(item)
    }
  })
  return treeList
}

The converted tree-type array structure renders the result.
insert image description here
The array methods used here include, forEach is used to loop through the array, and map is used to map the Id.

Summarize

In this article, we explored some commonly used array methods that help us perform various operations and transformations on arrays. We introduced some commonly used array methods, including adding and removing elements, merging and splitting arrays, and sorting and searching arrays. We also learned how to use iterative methods to traverse arrays and learned about some advanced array operations like filtering, mapping, etc. By learning these array methods, we can process array data more efficiently and flexibly, improving programming efficiency and code quality. Practice makes perfect !

Guess you like

Origin blog.csdn.net/m0_57524265/article/details/131680964