数组算法排序实现

重写 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' }
相关推荐
shehuiyuelaiyuehao8 分钟前
算法31,前缀和,可被k整除的子数组
数据结构·python·算法
hzxpaipai1 小时前
企业官网技术架构拆解:前端、后台、数据库、服务器如何协同
前端·数据库·架构
203号居民2 小时前
LeetCode hot 100 — 141. 环形链表2
算法·leetcode·链表
玖玥拾2 小时前
LeetCode 202 快乐数
算法·leetcode
LuminousCPP2 小时前
数据结构-二叉树(六):BFS层序遍历与完全二叉树判断|复用链式队列 + (N_0=N_2+1) 性质证明
c语言·数据结构·笔记·算法·二叉树·宽度优先
ZhouDevin3 小时前
算法论文/数据集3——CLD(TMLR2025)压缩训练集,仅保留对验证集有益的样本
人工智能·深度学习·算法·计算机视觉
深念Y3 小时前
Lenovo XiaoXinAir 14 — 性能模式切换
前端·网络
Tim_103 小时前
【LeetCode】29、两数相除
算法·leetcode·职场和发展
计算机魔术师4 小时前
Meta突然杀进第一梯队:一个新模型,把AI推理成本打下来8倍
前端