我有一组数字,我需要确保它们是唯一的。我在互联网上找到了下面的代码片段,它工作得很好,直到数组中有一个零。我在Stack Overflow上找到了另一个脚本,看起来几乎与它完全一样,但它不会失败。

所以为了帮助我学习,有人能帮我确定原型脚本哪里出错吗?

Array.prototype.getUnique = function() {
 var o = {}, a = [], i, e;
 for (i = 0; e = this[i]; i++) {o[e] = 1};
 for (e in o) {a.push (e)};
 return a;
}

重复问题的更多答案:

从JS数组中删除重复值

类似的问题:

获取数组中的所有非唯一值(即:重复/多次出现)


当前回答

您也可以使用underscore.js。

控制台日志(_.uniq([1,2,1,3,1,4]));<script src=“http://underscorejs.org/underscore-min.js“></script>

其将返回:

[1, 2, 3, 4]

其他回答

ES6/ES2015更新答案:使用Set和排列运算符(感谢le-m),单线解决方案为:

let uniqueItems = [...new Set(items)]

哪个会返回

[4, 5, 6, 3, 2, 23, 1]

不扩展Array.prototype(据说这是一种糟糕的做法)或使用jquery/下划线,您可以简单地过滤数组。

通过保留最后一次出现:

    function arrayLastUnique(array) {
        return array.filter(function (a, b, c) {
            // keeps last occurrence
            return c.indexOf(a, b + 1) < 0;
        });
    },

或首次出现:

    function arrayFirstUnique(array) {
        return array.filter(function (a, b, c) {
            // keeps first occurrence
            return c.indexOf(a) === b;
        });
    },

嗯,它只是javascript ECMAScript 5+,这意味着只有IE9+,但它很适合用原生HTML/JS(Windows应用商店应用程序、Firefox OS、Sencha、Phonegap、Titanium…)开发。

您可以使用Ramda.js(一个功能性javascript库)来执行此操作:

var unique=R.uniq([1,2,1,3,1,4])console.log(唯一)<script src=“https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js“></script>

var a = [1,4,2,7,1,5,9,2,4,7,2]
var b = {}, c = {};
var len = a.length;
for(var i=0;i<len;i++){
  a[i] in c ? delete b[a[i]] : b[a[i]] = true;
  c[a[i]] = true;
} 

// b contains all unique elements

这里的许多答案可能对初学者没有帮助。如果数组的重复数据消除很困难,他们真的会知道原型链,甚至jQuery吗?

在现代浏览器中,一个干净而简单的解决方案是将数据存储在一个集合中,该集合被设计为一个唯一值列表。

const cars=[“沃尔沃”、“吉普”、“沃尔沃”,“林肯”、“林肯”和“福特”];constuniqueCars=Array.from(新集合(cars));console.log(uniqueCars);

Array.from用于将Set转换回Array,以便您可以轻松访问数组所具有的所有很棒的方法(功能)。同样的事情还有其他方法。但您可能根本不需要Array.from,因为Sets有很多有用的功能,比如forEach。

如果您需要支持旧的Internet Explorer,因此无法使用Set,那么一种简单的方法是将项目复制到新阵列中,同时预先检查它们是否已在新阵列中。

// Create a list of cars, with duplicates.
var cars = ['Volvo', 'Jeep', 'Volvo', 'Lincoln', 'Lincoln', 'Ford'];
// Create a list of unique cars, to put a car in if we haven't already.
var uniqueCars = [];

// Go through each car, one at a time.
cars.forEach(function (car) {
    // The code within the following block runs only if the
    // current car does NOT exist in the uniqueCars list
    // - a.k.a. prevent duplicates
    if (uniqueCars.indexOf(car) === -1) {
        // Since we now know we haven't seen this car before,
        // copy it to the end of the uniqueCars list.
        uniqueCars.push(car);
    }
});

为了使其立即可重用,让我们将其放在函数中。

function deduplicate(data) {
    if (data.length > 0) {
        var result = [];

        data.forEach(function (elem) {
            if (result.indexOf(elem) === -1) {
                result.push(elem);
            }
        });

        return result;
    }
}

所以为了消除重复,我们现在就这样做。

var uniqueCars = deduplicate(cars);

当函数完成时,重复数据消除(cars)部分将成为我们命名为result的部分。

只需将您喜欢的任何数组的名称传递给它即可。