简体   繁体   English

Javascript:使用键从数组中查找重复的值

[英]Javascript: Find douplicated values from array with keys

Title is pretty much self explanatory... 标题几乎可以自我解释...

I want to be able to find duplicated values from JavaScript array. 我希望能够从JavaScript数组中找到重复的值。

The array keys can be duplicated so I need to validate only the array values. 数组键可以重复,因此我只需要验证数组值。

Here is an example : 这是一个例子:

var arr=[
    Ibanez:     'JoeSatriani',
    Ibanez:     'SteveVai',
    Fender:     'YngwieMalmsteen',
    Fender:     'EricJohnson',
    Gibson:     'EricJohnson',
    Takamine:   'SteveVai'
];

In that example: 在该示例中:

the key is the guitar brand the value is the guitar player name. 关键是吉他品牌,价值是吉他演奏者的名字。

So: 所以:

If there is duplicated keys (like: Ibanez or Fender ) as on that current example that is OK :-) 如果存在与当前示例相同的重复键(例如: IbanezFender ),则可以:-)

But

If there is duplicated values (like: EricJohnson or SteveVai ) I'm expecting to get (return) that error: 如果存在重复的值(例如: EricJohnsonSteveVai ),我期望得到(返回)该错误:

EricJohnson,SteveVai

You can't have associative arrays in Javascript. 您不能在Javascript中使用关联数组。 You can create an array of objects, like: 您可以创建一个对象数组,例如:

var arr=[
    {Ibanez:     'JoeSatriani'},
    {Ibanez:     'SteveVai'},
    {Fender:     'YngwieMalmsteen'},
    {Fender:     'EricJohnson'},
    {Gibson:     'EricJohnson'},
    {Takamine:   'SteveVai'}
];

Then you'll need a for...in loop to go over every object in the array, create a new array of values and check that for duplicates, which is also not very straightforward - basically you'll want to sort the array and make sure no value is the same as the one after it. 然后,您需要一个for...in循环来遍历数组中的每个对象,创建一个新的值数组并检查是否存在重复项,这也不是很简单-基本上,您需要对数组进行排序并确保没有任何值与后面的值相同。

var arrayOfValues = [];

arr.forEach(function(obj){
    for(var prop in obj)
        arrayOfValues.push(obj[prop]);
});

arrayOfValues.sort(); // by default it will sort them alphabetically

arrayOfValues.forEach(function(element,index,array){
   if(array[index+1] && element==array[index+1])
     alert("Duplicate value found!");
});

First of all, object keys can not be repeated. 首先,对象键不能重复。

This means that: 这意味着:

({
    "Fender": "Jim",
    "Fender": "Bob"
})["Fender"]

Would simply return: "Bob". 只需返回:“鲍勃”。

However, I did make a code that could allow you to find duplicates in values, but as I said, the key will have to be unique: 但是,我确实编写了一个代码,可以让您查找值中的重复项,但是正如我所说的,密钥必须是唯一的:

var arr = {
    Ibanez: 'EricJohnson',
    Fender: 'YngwieMalmsteen',
    Gibson: 'EricJohnson',
    Takamine: 'SteveVai',
    "Takamine2": 'SteveVai'
};

function contains(a, obj) {
    for (var i = 0; i < a.length; i++) {
        if (a[i] === obj) {
            return true;
        }
    }
    return false;
}

var track = [];
var exists = [];
for (var val in arr) {

    if (contains(track, arr[val])) {
        exists.push(arr[val]);
    } else {
        track.push(arr[val])
    }
}

alert(exists)

You can see it working here: http://jsfiddle.net/dr09sga6/2/ 您可以在这里看到它的工作: http : //jsfiddle.net/dr09sga6/2/

As others have commented, the example array you provided isn't a valid JavaScript array. 正如其他人所评论的那样,您提供的示例数组不是有效的JavaScript数组。 You could, however, keep a list for each guitar type: 但是,您可以保留每种吉他类型的列表:

var mapping = {
    Ibanez:     ['JoeSatriani','SteveVai'],
    Fender:     ['YngwieMalmsteen','EricJohnson']
    Gibson:     ['EricJohnson'],
    Takamine:   ['SteveVai']
];

Or a list of each guitar/musician pair: 或每个吉他/音乐家对的列表:

var pairs = [
    ['Ibanez','JoeSatriani'],
    ['Ibanez','SteveVai'],
    ['Fender','YngwieMalmsteen'],
    ['Fender','EricJohnson'],
    ['Gibson','EricJohnson'],
    ['Takamine','SteveVai']
];

Your solution is going to depend on which pattern you go with. 您的解决方案将取决于您采用哪种模式。 However, in the second case it can be done in one chained functional call: 但是,在第二种情况下,可以通过一个链接的函数调用来完成:

pairs.map(function(e) {return e[1]})  // Discard the brand names
.sort()  // Sort by artist
.reduce(function(p,c,i,a){
  if (i>0 && a[i]==a[i-1] && !p.some(function(v) {return v == c;})) p.push(c);
  return p;
},[]);  //Return the artist names that are duplicated

http://jsfiddle.net/mkurqmqd/1/ http://jsfiddle.net/mkurqmqd/1/

To break that reduce call down a bit, here's the callback again: 为了稍微reduce调用的次数,以下是回调:

function(p,c,i,a){
      if (i>0 
          && a[i]==a[i-1] 
          && !p.some(function(v) {
             return v == c;
          })) 
            p.push(c);
      return p;
}

reduce is going to call our callback for each element in the array, and it's going to pass the returned value for each call into the next call as the first parameter ( p ). reduce将为数组中的每个元素调用回调函数,并将每个调用的返回值作为第一个参数( p )传递给下一个调用。 It's useful for accumulating a list as you move across an array. 当您在数组中移动时,这对于累积列表很有用。

Because we're looking back at the previous item, we need to make sure we don't go out of bounds on item 0. 因为我们正在回顾上一个项目,所以我们需要确保我们不会超出项目0的范围。

Then we're checking to see if this item matches the previous one in the (sorted) list. 然后我们检查该项目是否与(已排序)列表中的上一个项目匹配。

Then we're checking (with Array.prototype.some() ) whether the value we've found is ALREADY in our list of duplicates...to avoid having duplicate duplicates! 然后,我们要检查(使用Array.prototype.some() )在重复列表中是否找到已经存在的值...以避免重复!

If all of those checks pass, we add the name to our list of duplicate values. 如果所有这些检查均通过,则将名称添加到重复值列表中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM