Skip to main content

数组相关

创建数组

// reactjs 中
Array(10).fill(1).map( () => <div></div/> )
let items = new Array(3);
let items = [1,2,3]

// 生成从0-9的数组
new Array(10).fill(1).map((v,i)=>i)

创建指定长度数组

// 创建一个3长度的数组,内容用0来填充
const arr = Array(3).fill(0)

判断是否数组

let arr = [1,2,3]
let res = Array.isArray(arr) // true

数组转字符串

  • join()
const Commands = ["npm", "-v"];

console.log(Commands.join(" ")); // npm -v
  • toString()
const Commands = ["npm", "-v"];

console.log(Commands.toString()); // npm, -v

删除元素

删除指定索引的元素

let index = 3
let test = [1,2,3,4,5]

// index: 删除index下标的元素
// 1: 删除1个
test.splice(index, 1)

删除指定的元素

const data = ['aa', 'bb', 'cc']


数组累计

Array.reduce

const tar = "1ttasdfvvzxcsdfasdf";

const 累计结果 = tar.split("").reduce((a,b)=>{
// 此处 如果a是第一次遍历,a就是{},首次传入的第二个参数
// 如果a已经是非第一次遍历,这里的a值得是上一次遍历运行是return的结果

return xxxx // 这里将作为下一次遍历时的a
}, {})

数组遍历

for...in

var a = [1, 2, 3];
for (var key in a) {
console.log(a[key]);
}

for...of

// (ES6)
var arr = ['a','b','c'];
for(let item of arr) {
console.log(item);
}
var name = ['Peter','Stark','Jack'];
// for 循环
for(var i = 0; i < name.length; i++) {
console.log(name[i]);
}
var name = ['Peter','Stark','Jack'];
// 先缓存 name.length
for(var i = 0, len = name.length; i < len; i++) {
console.log(name[i]);
}

forEach

every


map


filter


数组去重

替换元素

splice

删除:

语法:Array.splice(开始删除的位置, 要删除元素的数量)

const testList = [0, 1, 2, 3, 4, 5];

let removeIndex = 3;
let removeCount = 1;

let removeItem = testList.splice(removeIndex, removeCount);

console.log('removeItem: ', testList);// [0, 1, 2, 3, 4, 5]

插入|替换:

语法:Array.splice(插入位置, 0, 要插入的数据)Array.splice(插入位置, 要替换的数量, 要插入的数据)

const testList = [0, 1, 2, 3, 4, 5];

let removeIndex = 3;
let removeCount = 1;
let newItems = [2.5, 3.5];

let removeItem = testList.splice(removeIndex, 1, ...newItems);

console.log('testList: ', testList);
// [ 0, 1, 2, 2.5, 3.5, 4, 5 ] // 3被替换

数组筛选

多维数组 reduce

// 假设多维数组类型定义如下
type Person = [string, number];
const arr: Person[] = [
["Alice", 25],
["Bob", 30],
["Charlie", 28],
];

// 使用 reduce 查找 age 最大的行
const maxAgeRow = arr.reduce((maxRow, currentRow) => {
return currentRow[1] > maxRow[1] ? currentRow : maxRow;
}, arr[0]);

// 单行形式
const searchIndex = 1
const maxAgeRow = arr.length ? arr.reduce((max, row) => (row[searchIndex] > max[searchIndex] ? row : max)) : null;

console.log("Age 最大的行:", maxAgeRow);

包装函数

// 包装函数
function findMaxAgeRow(arr: Person[], searchIndex:number): Person | null {
// 如果数组为空,直接返回 null
if (arr.length === 0) {
return null;
}

// 假设第一行是 age 最大的行
let maxAgeRow = arr[0];

// 遍历数组的其余部分,找到 age 最大的行
for (let i = 1; i < arr.length; i++) {
const currentRow = arr[i];
if (currentRow[searchIndex] > maxAgeRow[searchIndex]) {
maxAgeRow = currentRow;
}
}

// 返回找到的最大 age 行
return maxAgeRow;
}

数组查找

查找一个元素是否在数组里

  • find(callback)
let numbers = [1, 2, 3, 4, 5];
console.log(numbers.find(n => n > 3)); // 4
console.log(numbers.findIndex(n => n > 3)); // 3
  • includes(searchElement, fromIndex):boolean
[1, 2, 3].includes(2);     // true
[1, 2, 3].includes(4); // false
[1, 2, NaN].includes(NaN); // true

数组取最大、最小

  • ES5
// string
Math.max.apply(Math, array.map(function (el) { return el.length }));
  • ES6
// number
const arr = [1,2,3,4,5,6,7,8,9];
Math.max(...arr); // 9
Math.min(...arr); // 1

// string
let max = Math.max(...arr.map(item => item.length))

合并数组

let arr1 = [20, 30];

// ES6 concat
let arr2 = arr1.concat([60, 80]); // [20, 30, 60, 80]

// 扩展运算符
let arr2 = [...arr1, 60, 80]; // [20, 30, 60, 80]

数组排序

lodash

import { shuffle } from "lodash";

const arr = shuffle([1,2,3])

sort + random

function shuffle(arr) {
return arr.sort(() => Math.random() - 0.5);
}

Fisher-Yates算法

function shuffle(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}

sort排序对象数组

const data = [
{x, y, z},
{x, y, z},
{x, y, z}
]

data.sort((a, b) => b.y - a.y);

反转数组

const arr = [1,2,3]

// 在原数组基础上反转
arr.reverse()

log({arr})
const arr = [1,2,3]

const rever_arr = arr.toReversed()

log({rever_arr})

根据长度重复数组

export function extendArray<T>(length: number, arr: T[]): T[] {
if (length <= 0 || arr.length === 0) {
return [];
}
if (arr.length >= length) {
return arr.slice(0, length);
}
const repeatTimes = Math.ceil(length / arr.length);
const repeated = Array(repeatTimes).fill(arr).flat();
return repeated.slice(0, length);
}


原地洗牌

function shuffleArray<T>(array: T[]): T[] {
// 注意这里用 let m = array.length 而不是 const
for (let m = array.length; m > 0; m--) {
// 生成 [0, m) 范围内的随机索引
const randomIndex = Math.floor(Math.random() * m);
// ES6 解构赋值交换元素
[array[m - 1], array[randomIndex]] = [array[randomIndex], array[m - 1]];
}
return array;
}

非破坏性洗牌

function shuffleCopy<T>(array: readonly T[]): T[] {
// 创建副本避免修改原数组
const copy = [...array];
for (let i = copy.length - 1; i > 0; i--) {
// 生成 [0, i] 的随机索引(包含i)
const j = Math.floor(Math.random() * (i + 1));
// 传统交换方式(兼容性更好)
const temp = copy[i];
copy[i] = copy[j];
copy[j] = temp;
}
return copy;
}