数组算法排序实现

重写 Array.filter()

复制代码
javascript复制代码Array.prototype.myFilter = function(callback, thisArg) {
    const result = [];
    for (let i = 0; i < this.length; i++) {
        if (callback.call(thisArg, this[i], i, this)) {
            result.push(this[i]);
        }
    }
    return result;
};
​
// 测试
const arr = [1, 2, 3, 4, 5];
const filteredArr = arr.myFilter(num => num > 2);
console.log(filteredArr); // [3, 4, 5]

算法1:合并两个已排序的数组

复制代码
javascript复制代码function mergeSortedArrays(arr1, arr2) {
    let i = 0, j = 0;
    const result = [];
​
    while (i < arr1.length && j < arr2.length) {
        if (arr1[i] < arr2[j]) {
            result.push(arr1[i]);
            i++;
        } else {
            result.push(arr2[j]);
            j++;
        }
    }
​
    // 处理剩余元素
    return result.concat(arr1.slice(i)).concat(arr2.slice(j));
}
​
// 测试
const arr1 = [1, 3, 5, 7];
const arr2 = [2, 4, 6, 8];
console.log(mergeSortedArrays(arr1, arr2)); // [1, 2, 3, 4, 5, 6, 7, 8]

算法2:数值序列化(每隔三位一个逗号)

复制代码
javascript复制代码function numberWithCommas(num) {
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
​
// 测试
const num = 1234567890;
console.log(numberWithCommas(num)); // 1,234,567,890

算法3:格式化 query 字符串

复制代码
javascript复制代码function parseQueryString(queryString) {
    const queryObj = {};
    const pairs = queryString.replace(/^\?/, '').split('&');
​
    for (const pair of pairs) {
        const [key, value] = pair.split('=');
        if (queryObj[key]) {
            if (Array.isArray(queryObj[key])) {
                queryObj[key].push(decodeURIComponent(value));
            } else {
                queryObj[key] = [queryObj[key], decodeURIComponent(value)];
            }
        } else {
            queryObj[key] = decodeURIComponent(value);
        }
    }
​
    return queryObj;
}
​
// 测试
const queryString = '?a=1&a=2&b=3';
console.log(parseQueryString(queryString)); // { a: ['1', '2'], b: '3' }
相关推荐
从零开始的代码生活_17 分钟前
C++ stack、queue 与 priority_queue:容器适配器原理与实战
开发语言·c++·后端·学习·算法
晚笙coding19 分钟前
LeetCode 226. 翻转二叉树(Invert Binary Tree)
算法·leetcode·职场和发展
爱勇宝22 分钟前
《道德经》第6章:别把团队的创造力用到枯竭
前端·后端
无双_Joney25 分钟前
[四期 - 4] NestJS专栏 - 征召一下大家的意见,非常想知道大家都想看看Nest的哪些方面
前端·后端·nestjs
彭亚川Allen28 分钟前
停更的这一年,All In AI、陪媳妇生娃、还考了个研
前端·后端·产品经理
2zcode42 分钟前
项目文档:基于MATLAB低采样率ISAR成像的快速稀疏重建算法研究
开发语言·算法·matlab
爱分享的程序猿-Clark1 小时前
【前端开发】前端开发者如何使用 Claude Code 快速搭建 React 项目!(小白都能学会的教程)
前端·react.js
哈里沃克1 小时前
编译与链接 - 02
算法
巴糖1 小时前
Embedding了解一些
算法
战族狼魂1 小时前
广东备案大模型超百款
人工智能·算法·大模型·大语言模型