JavaScript data structures and algorithms - arrays and common methods of arrays


1. splice() - cropping

splice() is often used to clip arrays and can receive three parameters.

  • Parameter 1: Start cropping from the first item in the array
  • Parameter 2: How many items to crop out
  • Parameter three (no need to pass): what data to append

1.1 Conventional clipping array

let arr = [1,2,3,4,5]
let arr1 = arr.splice(0,2)
console.log(arr)   // 输出结果:[3, 4, 5]
console.log(arr1)  // 输出结果:[1, 2]

1.2 After cropping and appending data

let arr = [1,2,3,4,5]
let arr1 = arr.splice(1,1,10,20,30)
console.log(arr)   // 输出结果:[1, 10, 20, 30, 3, 4, 5]
console.log(arr1)  // 输出结果:[2]

2. sort() - sorting

sort() is often used to sort arrays. It can not only sort simple arrays, but also sort objects based on a certain value in the object.

  • X - Y: Sort from small to large
  • Y - X: Sort from large to small

2.1 From small to large (X - Y)

 let arr = new Array(6,5,2,8,19,35,5)
 arr.sort((x,y)=>x-y)   // 从小到大排列
 console.log(arr)       // 输出结果:[2, 5, 5, 6, 8, 19, 35]

2.2 From largest to smallest (Y - X)

 let arr = new Array(6,5,2,8,19,35,5)
 arr.sort((x,y)=>y-x)   // 从小到大排列
 console.log(arr)       // 输出结果:[35, 19, 8, 6, 5, 5, 2]

2.3 Sort objects according to a certain value in the object

let arr = [
  {
    
    name: "张三",age: 25,},
  {
    
    name: "李四",age: 23,},
  {
    
    name: "王五",age: 30,},
];
// 根据 age ,从小到大排序
arr.sort((x, y) => x.age - y.age);
console.log(arr);
// 输出结果如下:
// [
//  {name: "李四",age: 23,},
//  {name: "张三",age: 25,},
//  {name: "王五",age: 30,},
// ]

3. concat() - connection

concat() can concatenate two arrays

let arr1 =new Array(1,2,3)
let arr2 =new Array(5,6,7)
// 将 arr1 与 arr2进行连接
let arr3= arr1.concat(arr2)
console.log(arr3);     // 输出结果;[1, 2, 3, 5, 6, 7]

// 将 arr1、arr2、10,11,12 进行连接
let arr4= arr1.concat(arr2,10,11,12)
console.log(arr4);    // 输出结果;[1, 2, 3, 5, 6, 7, 10, 11, 12]

4. every() - all values ​​satisfy the conditions

every() can traverse the array and the return value is a Boolean value

  • 所有项均满足条件时Returns true only when it is an array
  • Otherwise, return false

4.1 Having value does not meet the conditions

 let arr = new Array(10, 11, 12, 13, 14, 15);
 let result = arr.every((item) => item > 10);
 console.log(result)  // 输出结果:false。显然并非每一项都大于10

4.2 All conditions are met

let arr = new Array(10, 11, 12, 13, 14, 15);
let result = arr.every((item) => item < 20);
console.log(result)  // 输出结果:true。显然数组中的每一项都小于20

5. some() - at least one meets the conditions

some() can traverse the array and the return value is a Boolean value. Note the difference from every() method

  • array 至少一项满足条件时, returns true
  • Otherwise, return false

5.1 All values ​​do not satisfy the condition

 let arr = new Array(10, 11, 12, 13, 14, 15);
 let result = arr.every((item) => item > 20);
 console.log(result)  // 输出结果:false。显然数组中不存在任何一项大于20

5.2 At least one condition is met

 let arr = new Array(10, 11, 12, 13, 14, 15);
 let result = arr.every((item) => item > 14);
 console.log(result)  // 输出结果:true。显然数组中存在一项大于14

6. filter() - filter array

filter() is used to 过滤remove certain elements from an array and return the remaining elements

6.1 Filter even numbers

 let arr = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9);
 let arr2 = arr.filter((item) => {
    
    
   return item % 2 != 0;
 });
 console.log(arr2)   // 输出结果:[1, 3, 5, 7, 9]

6.2 Filter objects in an array

let arr = [
   {
    
     name: "张三", age: 15 },
   {
    
     name: "李四", age: 25 },
   {
    
     name: "王五", age: 30 },
   {
    
     name: "陈皮", age: 40 },
 ];
 let arr2 = arr.filter((item) => {
    
    
   // 可自行设置过滤条件
   return item.age > 25;
 });
 console.log(arr2);  // 输出结果:[{ name: "王五", age: 30 },{ name: "陈皮", age: 40 }]

7. map() - returns a new array

Returns a new array, the elements in the array are the values ​​of the original array after calling the function.

let arr = new Array(10, 11, 12, 13, 14, 15);
let arr2 = arr.map((item) => item + "你好"); // 返回新数组,进行数据拼接
console.log(arr2)   // 输出结果:["10你好","11你好","12你好","13你好","14你好","15你好"]

8. forEach() - loop traversal

The most commonly used loop traversal method by individuals, it is very fast and easy to use.

8.1 Abbreviation

let arr = [
  {
    
    name:'张三',age:15},
  {
    
    name:'李四',age:23},
  {
    
    name:'王五',age:32},
  {
    
    name:'陈皮',age:27},
]
// 只用到item,不用index时,可以省略括号
arr.forEach(item=>{
    
    
  // 拿到数组中的每一项,即可写入对应的逻辑代码
  console.log(item)
})

8.2 index

let arr = [
  {
    
    name:'张三',age:15},
  {
    
    name:'李四',age:23},
  {
    
    name:'王五',age:32},
  {
    
    name:'陈皮',age:27},
]
arr.forEach((item,index)=>{
    
    
  // 可以拿到数组中的每一项,以及对应性的 index 
  console.log(item,index)
})

9. Introduction to reduce() method

The reduce() method executes a reduce function you provide (in ascending order) on each element in the array, summarizing its results into a single return value. The reduce method can do a lot of things. Reduce can do everything that loop traversal can do, such as array summation, array multiplication, the number of occurrences of elements in an array, array deduplication, etc.

9.1 Array accumulation

let arr = [1, 2, 3, 4, 5];
// 下一次循环时,item1 + item2 的值会赋值给 item1
let arr2 = arr.reduce((item1, item2) => item1 + item2);
console.log(arr2);  // 输出结果:15

9.2 Array cumulative multiplication

let arr = [1, 2, 3, 4, 5];
// 下一次循环时,item1 * item2 的值会赋值给 item1
let arr2 = arr.reduce((item1, item2) => item1 * item2);
console.log(arr2);  // 输出结果:120

9.3 Array deduplication

let arr = [1, 3, 5, 7, 9, 1, 3, 5];
let arr1 = arr.reduce((total, current, index) => {
    
    
  // 判断total中是否包含current
  if (!total.includes(current)) {
    
    
    return total.concat(current);
  } else {
    
    
    return total;
  }
}, []);
console.log(arr1);   // 输出结果:[1,3,5,7,9]

9.4 Convert a two-dimensional array to a one-dimensional array

let arr = [[1,2],[3,4],[5,6]]
let arr1 = arr.reduce((total,current)=>{
    
       // 方法二
  return total.concat(current)
},[])
console.log(arr1)  // 输出结果:[1,2,3,4,5,6]

Interlude, here is a simpler way to convert a two-dimensional array into an array

let arr = [[1,2],[3,4],[5,6]]
// 只需一行代码,即可将二维数组,转为一维数组
let arr1 = arr.flat(Infinity)
console.log(arr1)  // 输出结果:[1,2,3,4,5,6]

9.5 Count the occurrences of elements

let arr = ["王", "李", "王", "张", "张", "张"];
let num = arr.reduce((total, current) => {
    
    
  //  current in total current 是否在total中
  if (current in total) {
    
    
    total[current]++;
  } else {
    
    
    total[current] = 1;
  }
  return total;
},{
    
    });
console.log(num);  // 输出结果:{王: 2, 李: 1, 张: 3}

10. iterator object

There are multiple iterator objects, and different values ​​can be obtained through different iterator objects.

  • arr.keys() gets the key of each item in the array
  • arr.values() gets the value of each item in the array
  • arr.entries() gets each key-value pair in the array

10.1 Simple for loop

let arr = [10, 11, 12, 13, 14];
for(let item of arr){
    
    
  console.log(item)  // 输出结果: 10, 11, 12, 13, 14
}

10.2 The iterator object gets the key-value pairs of the array

let arr = [10, 11, 12, 13, 14];
for(let item of arr.entries(){
    
    
  console.log(item)
}

Output result:
Insert image description here

10.3 Iterator objects only get keys

let arr = [10, 11, 12, 13, 14];
for (let item of arr.keys()) {
    
    
  console.log(item);
}

Output result:
Insert image description here

10.4 Iterator objects only get values

let arr = [10, 11, 12, 13, 14];
for (let item of arr.values()) {
    
    
  console.log(item);
}

Output result:
Insert image description here


11. Array.from()

Array.from() can convert array-like structures into arrays

function test() {
    
    
  // 通过 Array.from() 将 arguments 转为数组
  console.log(Array.from(arguments));
  // 转为数组后可以调用数组的方法
  Array.from(arguments).forEach(item=>{
    
    
    console.log(item)
  })
}
test(1, 2, 3);

Output result:
Insert image description here


12. Search - indexOf()

arr.indexOf can get the position of the element in the array

  • If there is this element, return its index
  • If there is no such element, return -1
let arr = [10, 11, 12, 13, 14, 15];
console.log(arr.indexOf(11), "11的index");  // 输出结果:1 '11的index'
console.log(arr.indexOf(20), "20的index");  // 输出结果:-1 '20的index'

13. Search - find()

find(), 从头到尾search, return the first value that meets the conditions

let arr = [10, 11, 12, 13, 14, 15];
let res = arr.find((item) => item > 10);
console.log(res)  // 输出结果:11

14. Search - findLast()

findLast(), 从尾到头search, return the first value that meets the conditions

let arr = [10, 11, 12, 13, 14, 15];
let res = arr.find((item) => item < 14);
console.log(res)  // 输出结果:13

15. Search - findIndex()

findIndex(), 从头到尾search, return the index value of the first data that meets the conditions

let arr = [10, 11, 12, 13, 14, 15];
let res = arr.find((item) => item > 10);
console.log(res)  // 输出结果:1

16. Search - findLastIndex()

findLastIndex(), 从尾到头search, return the index value of the first data that meets the conditions

let arr = [10, 11, 12, 13, 14, 15];
let res = arr.find((item) => item < 14);
console.log(res)  // 输出结果:3

Guess you like

Origin blog.csdn.net/qq_61402485/article/details/132093908