简体   繁体   English

检查数组中的重复项

[英]Check for duplicates in an array

I have a function that will check a serialized form data if there are duplicates values in it. 我有一个函数,如果其中有重复的值,它将检查序列化的表单数据。

    s = $('#multiselectForm').serialize();
    var x = [];
    var y = [];
    x = s.split("&");
    for (var i = x.length - 1; i >= 0; i--) {
        y.push(x[i].split("="));
    };
    var c = 0;
    var e = 0;
    for (var i = y.length - 1; i >= 0; i--) {
        if (y[i][1] == y[c][1]) {
            e++;
            $('.duplicateAlert').show();
        } else {
            $('.duplicateAlert').hide();
        };
        c++;
    };

Basically, what it does is split the string produced by the serialize() function and push the data into arrays. 基本上,它所做的是将serialize()函数产生的字符串拆分并将数据推送到数组中。

The array I'm trying to parse looks like this: 我要解析的数组如下所示:

Array [
    Array [
    0: 'my_field1',
    1: 'val1'
    ],

    Array [
    0: 'my_field2'
    1: 'val2'
    ],

    Array [
    0: 'my_field3'
    1: 'val1'
    ]
]

Are there any better ways to do the same task? 有没有更好的方法来完成相同的任务? Maybe even shorter? 也许更短?

  1. Create an empty array to hold the matches 创建一个空数组来保存匹配项
  2. Loop through the array. 遍历数组。 On each iteration... 在每次迭代中...
    1. Loop through the matches array and check if an item with the same value exists. 遍历match数组,并检查是否存在具有相同值的项目。 If it does, set the matched flag. 如果是这样,请设置匹配标志。
    2. Check if the matched flag has been set 检查是否已设置匹配标志
      1. if so, alert the user 如果是这样,提醒用户
      2. if not add the item to matches. 如果没有,则将该项目添加到匹配项中。

var array = [
    [ 'my_field1', 'val1' ],
    [ 'my_field2', 'val2' ],
    [ 'my_field3', 'val1' ],
    [ 'my_field4', 'val2' ],
    [ 'my_field5', 'val3' ]
], matches = [], match = false;

for(var i = 0, j = array.length; i < j; i++) {
    match = false;
    for(var k = 0, l = matches.length; k < l; k++) {
        if(matches[k][1] == array[i][1]) {
            match = true;
        }
    }
    if(match) alert('Duplicate!');
    else matches.push(array[i]);
}

If you have serialised data in the typical format like: 如果您已按照以下典型格式对数据进行序列化:

var data = 'foo=foo&bar=bar%26bar&blah=foo';

then you can check it for duplicates by getting the values between = and & and looking for dupes: 那么您可以通过获取=&之间的值并查找重复项来检查它是否重复:

var seen = {};
var hasDupes = (data.match(/=[^&]+/g) || []).some(function(v){
    return v in seen || (seen[v] = true) && false;
});

console.log(hasDupes);  // true

The idea behind: 背后的想法:

data.match(/=[^&]+/g) || []

is that match can return null if no matches are found, so if that happens the expression returns an empty array and the following call to some is called on the empty array (and returns false) rather than null , and hence doesn't throw the error that it would otherwise. 是如果找不到匹配项,则match可以返回null ,因此,如果发生这种情况,该表达式将返回一个空数组,并且在空数组上调用对some的以下调用(并返回false),而不是null ,因此不会抛出否则会出现错误。

However, I still think it would be more efficient to check the form control values directly before serialising, rather than serialising the form then checking the result. 但是,我仍然认为在序列化之前直接检查表单控制值会比序列化然后检查结果的效率更高。

You can do that with a function like: 您可以使用类似的功能来做到这一点:

function checkDupValues(form) {
  var value,
      seen = {},
      controls = form.elements;

  for (var i=0, iLen=controls.length; i<iLen; i++) {
    // Might want to check type of control here and ignore buttons, etc.
    value = controls[i].value;

    // Ignore empty controls?
    if (value != '' && value in seen) {
      // have a duplicate value that is not ''
      alert('have dupes');

    } else {
      seen[value] = true;
    }
  }
}

Try this although its not much shorter: 尝试一下,尽管它并不短:

var array = [
  [
    'my_field1',
    'val1'
  ],

  [
    'my_field2',
    'val2'
  ],

  [
    'my_field3',
    'val1'
  ]
]

var originals = [];
var duplicates = [];
for (a in array) {
  if (originals.indexOf(array[a][1] == -1)) {
    originals.push(array[a][1])
  } else {
    duplicates.push(array[a])
  }
}
alert('duplicates: ' + duplicates.join(', '));

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

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