2025年你一定要知道的20种数组处理方法

115 阅读4分钟

1. 数组创建

const array = [1, 2, 3, 4, 5]; // 使用字面量创建数组
const array2 = new Array(10); // 创建一个长度为10的空数组

2. 添加元素

  • push() :向数组末尾添加一个或多个元素,并返回新的长度。

    array.push(6); // [1, 2, 3, 4, 5, 6]
    

  • unshift() :向数组开头添加一个或多个元素,并返回新的长度。

    array.unshift(0); // [0, 1, 2, 3, 4, 5, 6]
    

3. 删除元素

  • pop() :从数组末尾删除一个元素,并返回该元素。

    const lastElement = array.pop(); // [0, 1, 2, 3, 4, 5], lastElement = 6
    

  • shift() :从数组开头删除一个元素,并返回该元素。

    const firstElement = array.shift(); // [1, 2, 3, 4, 5], firstElement = 0
    

4. 查找元素

  • indexOf() :查找指定元素的索引,未找到返回 -1。

    const index = array.indexOf(3); // 2
    

  • includes() :检查数组是否包含某个值,返回 true 或 false。

    const hasThree = array.includes(3); // true
    

5. 遍历数组

  • forEach() :对数组的每个元素执行一次提供的函数。

    array.forEach((item) => {
        console.log(item);
    });
    

  • map() :返回一个新数组,数组中的元素是通过调用提供的函数处理原数组中的每个元素得出的。

    const squares = array.map((num) => num * num); // [1, 4, 9, 16, 25]
    

6. 过滤数组

  • filter() :返回一个新数组,包含通过所提供函数测试的所有元素。

    const evenNumbers = array.filter((num) => num % 2 === 0); // [2, 4]
    

7. 排序与反转

  • sort() :按升序排序数组元素,默认是按字符编码顺序。

    array.sort(); // [-1, 0, 1, 2, 3, 4, 5]
    

  • reverse() :反转数组中的元素。

    array.reverse(); // [5, 4, 3, 2, 1, 0]
    

8. 合并与分割

  • concat() :合并两个或多个数组,返回一个新数组。

    const newArray = array.concat([6, 7, 8]); // [1, 2, 3, 4, 5, 6, 7, 8]
    

  • slice() :返回一个选定范围的新数组,不会修改原数组。

    const subArray = array.slice(1, 3); // [2, 3]
    

9. 拼接与连接

  • join() :将数组中的所有元素连接成一个字符串。

    const joined = array.join('-'); // "1-2-3-4-5"
    

10. 数组去重

  • 使用 Set 可以快速进行数组去重。

    const uniqueArray = [...new Set(array)]; // [1, 2, 3, 4, 5]
    

11. 扁平化数组

如果你有包含嵌套数组的数组,可以使用 flat() 方法将其扁平化。

const nestedArray = [1, [2, 3], [4, [5, 6]]];
const flatArray = nestedArray.flat(2); // [1, 2, 3, 4, 5, 6]

12. 查找元素

  • find() :返回数组中满足提供的测试函数的第一个元素。如果没有找到,则返回 undefined
const foundElement = array.find((num) => num > 2); // 找到第一个大于2的元素

  • findIndex() :返回满足提供测试函数的数组元素的索引。如果没有找到,则返回 -1。
const indexOfFirstGreaterThanTwo = array.findIndex((num) => num > 2); // 返回第一个大于2的索引

13. 数组去重(额外方法)

除了使用 Set,下面是另一种使用 filter 和 indexOf 方法的去重方式:

const arrayWithDuplicates = [1, 2, 3, 1, 2, 4];
const uniqueArray = arrayWithDuplicates.filter((item, index) => {
    return arrayWithDuplicates.indexOf(item) === index;
}); // [1, 2, 3, 4]

14. 分组数组

可以使用 reduce() 方法将数组中的元素按属性分组。

const data = [
    { name: 'Alice', age: 25 },
    { name: 'Bob', age: 30 },
    { name: 'Alice', age: 28 }
];
const groupedByName = data.reduce((acc, obj) => {
    const key = obj.name;
    if (!acc[key]) {
        acc[key] = [];
    }
    acc[key].push(obj);
    return acc;
}, {});

15. 合并多个数组

除了使用 concat(),还有一种方法是使用扩展运算符(spread operator):

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const mergedArray = [...array1, ...array2]; // [1, 2, 3, 4, 5, 6]

16. 返回数组的随机元素

可以编写一个函数,随机返回数组中的一个元素:

const getRandomElement = (arr) => arr[Math.floor(Math.random() * arr.length)];
const randomElement = getRandomElement(array); // 返回数组中的随机元素

17. shuffle(洗牌)数组

使用 Fisher-Yates 算法可以将数组随机打乱:

const shuffleArray = (array) => {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]]; // 交换元素
    }
    return array;
};
const shuffled = shuffleArray(array); // 返回打乱后的数组

18. 查找并替换元素

通过遍历找到特定元素并进行替换:

const replaceElement = (array, oldElement, newElement) =>
    array.map(item => item === oldElement ? newElement : item);

const updatedArray = replaceElement(array, 2, 20); // 将2替换为20

19. 合并对象数组

如果有一个包含对象的数组,可以以某个属性合并对象:

const merged = data.reduce((acc, current) => {
    const x = acc.find(item => item.name === current.name);
    if (x) {
        x.age.push(current.age);
    } else {
        acc.push({ name: current.name, age: [current.age] });
    }
    return acc;
}, []);

20. 数组转为对象

可以将数组转换为对象,通常以数组的第一个元素作为键:

const arrayToObj = (array) => {
    return array.reduce((obj, item) => {
        obj[item[0]] = item[1];
        return obj;
    }, {});
};
const obj = arrayToObj([['name', 'Alice'], ['age', 25]]); 
// { name: 'Alice', age: 25 }