从JavaScript数组中删除重复 [英] Remove Duplicates from JavaScript Array

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

问题描述

这似乎是一个简单的需求,但是我花了很多时间试图做到这一点没有效果。我已经看过其他的问题,我没有找到我需要的。我有一个非常简单的JavaScript数组,如 peoplenames = new Array(Mike,Matt,Nancy,Adam,Jenny,Nancy,Carl / code>可能包含或不包含重复项,我需要简单地删除重复项,并将唯一值放在一个新的数组中。而已。我可以指出我尝试的所有代码,但我认为这是没用的,因为它们不起作用。如果有人这样做,可以帮助我,我真的很感激。 JavaScript或jQuery解决方案都可以接受。

This seems like such a simple need but I've spent an inordinate amount of time trying to do this to no avail. I've looked at other questions on SO and I haven't found what I need. I have a very simple JavaScript array such as peoplenames = new Array("Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"); that may or may not contain duplicates and I need to simply remove the duplicates and put the unique values in a new array. That's it. I could point to all the codes that I've tried but I think it's useless because they don't work. If anyone has done this and can help me out I'd really appreciate it. JavaScript or jQuery solutions are both acceptable.

推荐答案

var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
var uniqueNames = [];
$.each(names, function(i, el){
    if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
});

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

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