数组算法排序实现

重写 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' }
相关推荐
敲敲了个代码4 小时前
从硬编码到 Schema 推断:前端表单开发的工程化转型
前端·javascript·vue.js·学习·面试·职场和发展·前端框架
dly_blog5 小时前
Vue 响应式陷阱与解决方案(第19节)
前端·javascript·vue.js
消失的旧时光-19436 小时前
401 自动刷新 Token 的完整架构设计(Dio 实战版)
开发语言·前端·javascript
wadesir6 小时前
Rust中的条件变量详解(使用Condvar的wait方法实现线程同步)
开发语言·算法·rust
console.log('npc')6 小时前
Table,vue3在父组件调用子组件columns列的方法展示弹窗文件预览效果
前端·javascript·vue.js
用户47949283569156 小时前
React Hooks 的“天条”:为啥绝对不能写在 if 语句里?
前端·react.js
yugi9878386 小时前
基于MATLAB实现协同过滤电影推荐系统
算法·matlab
TimberWill6 小时前
哈希-02-最长连续序列
算法·leetcode·排序算法
Morwit6 小时前
【力扣hot100】64. 最小路径和
c++·算法·leetcode
我命由我123456 小时前
SVG - SVG 引入(SVG 概述、SVG 基本使用、SVG 使用 CSS、SVG 使用 JavaScript、SVG 实例实操)
开发语言·前端·javascript·css·学习·ecmascript·学习方法