从数组中完全删除重复项 [英] Completely removing duplicate items from an array

查看:36
本文介绍了从数组中完全删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有;

var array = [1,2,3,4,4,5,5];

我希望它是;

var newArray = [1,2,3];

我想完全删除重复项,而不是将它们保留为唯一值.有没有办法通过 reduce 方法来实现?

I want to remove the duplicates completely rather than keeping them as unique values. Is there a way achieve that through reduce method ?

推荐答案

你可以使用 Array#filterArray#indexOfArray#lastIndexOf 并仅返回共享相同索引的值.

You could use Array#filter with Array#indexOf and Array#lastIndexOf and return only the values which share the same index.

var array = [1, 2, 3, 4, 4, 5, 5],
    result = array.filter(function (v, _, a) {
        return a.indexOf(v) === a.lastIndexOf(v);
    });

console.log(result);

另一种方法是采用 Map 并将值设置为 false,如果之前已经看到过一个键.然后通过获取地图的值来过滤数组.

Another approach by taking a Map and set the value to false, if a key has been seen before. Then filter the array by taking the value of the map.

var array = [1, 2, 3, 4, 4, 5, 5],
    result = array.filter(
        Map.prototype.get,
        array.reduce((m, v) => m.set(v, !m.has(v)), new Map)
    );

console.log(result);

这篇关于从数组中完全删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆