用JS实现一个数组合并的方法(要求去重)

两个数组,a = [1,2,3], b = [2,3,4],要求合并后的数组为[1,2,3,4]

Array.prototype.unique = function(){
    var a = {};
    for(var i = 0; i < this.length; i++){
        if(typeof a[this[i]] == "undefined")
            a[this[i]] = 1;
    }
    this.length = 0;
    for(var i in a)
        this[this.length] = i;
    return this;
}
var a = [1,2,3];
var b = [2,3,4];
var c = a.concat(b).unique();

两个数组,a = [1,2,3], b = [2,3,4],要求合并后的数组为[1,4]

Array.prototype.unique2 = function(){
    var a = {},
        b = {},
        n = this.length;
    for(var i = 0; i < n; i++){
        if(typeof(b[this[i]]) != "undefined")
            continue;
        if(typeof(a[this[i]]) == "undefined"){
            a[this[i]] = 1;
        }else{
            b[this[i]] = 1;
            delete a[this[i]];
        }
    }
    this.length = 0;
    for(var i in a)
        this[this.length] = i;
    return this;
}
var a = [1,2,3,4];
var b = [2,3,5,7];
var d = a.concat(b).unique2();
要将JavaScript数组对象并后去重,你可以使用不同的方法。以下是几种常见的方法: 1. 使用Set对象:Set是ES6中的一个内置对象,它允许你存储唯一的值。你可以使用Set对象来并两个数组,并自动去除重复项。例如: ```javascript let arr1 = [1, 2, 3, 4, 5]; let arr2 = [7, 8, 9, 4, 5]; let mergedArray = [...new Set([...arr1, ...arr2])]; ``` 这里我们使用了扩展运算符(...)来将两个数组展开,然后通过Set对象去除重复项,并最终将结果转换为一个新的数组。 2. 使用concat()和filter()方法:你可以使用concat()方法将两个数组合并,然后使用filter()方法过滤出唯一的值。例如: ```javascript let arr1 = [1, 2, 3, 4, 5]; let arr2 = [7, 8, 9, 4, 5]; let mergedArray = arr1.concat(arr2).filter((item, index, array) => array.indexOf(item) === index); ``` 在这个例子中,我们先使用concat()方法将两个数组合并,然后使用filter()方法来过滤出只出现一次的值。我们使用indexOf()方法来检查当前元素在数组中的第一个索引位置,如果当前索引和第一个索引相同,则保留该元素。 3. 使用reduce()方法:你可以使用reduce()方法来迭代并两个数组,并在每次迭代时检查重复项。例如: ```javascript let arr1 = [1, 2, 3, 4, 5]; let arr2 = [7, 8, 9, 4, 5]; let mergedArray = arr1.reduce((accumulator, currentValue) => { if (!accumulator.includes(currentValue)) { accumulator.push(currentValue); } return accumulator; }, arr2); ``` 在这个例子中,我们使用reduce()方法来迭代arr1数组,并将结果存储在accumulator变量中。在每次迭代时,我们检查当前值是否已经存在于accumulator数组中,如果不存在,则将其添加到accumulator中。最后,将arr2数组作为初始值传递给reduce()方法。 这些是一些常见的方法,你可以根据你的需求选择其中一种来实现数组合并去重。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [JS数组并与去重](https://blog.csdn.net/zhengjingID/article/details/123429877)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值