首页 > JS - 算法 - 数组去重 - 重载 equal 运算的数组去重

JS - 算法 - 数组去重 - 重载 equal 运算的数组去重

20160512 修改:避免歧义


输入:

[ [ 1, 1 ], [ 1, 1 ], [ 1, -1 ], [ 1, -1 ], [ 1, 1 ], [ 1, -1 ] ]

定义形如 [ 1, 1 ] 的元素为向量

向量相等遵从以下算法:

function vectorEquality(u, v) {
    return u.length === v.length && !u.some((x, i) => x !== v[i]);
}

要求以以上算法为标准进行数组去重

即输出:

[ [ 1, 1 ], [ 1, -1 ] ]

要求:

尽量降低算法复杂度

尽量使用原生函数


先做出几点假设:
1.数组里都是数字数组,没有字母或者其他复杂对象;
2.[1,-1]和 [-1,1]我们将视为同一对象,两个中只存一个

实现:

var orginArray=[ [1,-1],[ 1, 1 ], [ 1, 1 ], [ 1, -1 ], [ 1, -1 ], [ 1, 1 ], [ 1, -1 ] ],//原数组
        newArray=[],//新数组用于接收去重后的数字数组
        keyMap={};//用于记录已经存在的键
    orginArray.map(function(_this){
        var _tempKey=_this.sort().toString();//将原数组元素自然排序并转换为字符串
        if(_tempKey in keyMap){//如果键在keyMap中,则说明新数组中已经有这个元素
            return;
        }
        //若键不在keyMap中,则把当前元素扔到新数组中,并用keyMap记录
        newArray.push(_this);
        keyMap[_tempKey]=_this;
        
    })
    
    console.info("去重后的数组:",newArray);
    
    
    

简单封装下:

Array.prototype.removeRepeat = function() {
    var orginArray = this, //原数组
        newArray = [], //新数组用于接收去重后的数字数组
        keyMap = {}; //用于记录已经存在的键
    orginArray.map(function(_this) {
        var _tempKey = _this.sort().toString(); //将原数组元素自然排序并转换为字符串
        if (_tempKey in keyMap) { //如果键在keyMap中,则说明新数组中已经有这个元素
            return;
        }
        //若键不在keyMap中,则把当前元素扔到新数组中,并用keyMap记录
        newArray.push(_this);
        keyMap[_tempKey] = _this;

    })
    return newArray;
}
var orginArray=[ [1,-1],[ 1, 1 ], [ 1, 1 ], [ 1, -1 ], [ 1, -1 ], [ 1, 1 ], [ 1, -1 ] ];
console.info("去重后的数组:",orginArray.removeRepeat());

var a =[ [ 1, 1 ], [ 1, 1 ], [ 1, -1 ], [ 1, -1 ], [ 1, 1 ], [ 1, -1 ] ];
var res= [...new Map(a.map(([a,b]) => [a+','+b,[a,b]])).values()]

推荐看看Lodash库


看看Lodash的_.uniq方法,这个库可以让你写出很优雅的代码。(类似java中的guava工具库)


如果都是简单对象 可以JSON化然后比较字符串

【热门文章】
【热门文章】