I am trying to detect whenever an array has a duplicate value and then
produce an alert to the user that a dupe exists with the value of the
dupe.
Reading 'Prototype & Scriptaculous IN ACTION', I have been able to
begin the coding to obtain the textarea values and sort the resultant
array. I am having trouble coding the duplicate value detection.
Here is my limited code:
var txtarea = $F('txtarea4').split(/[\n\r]+/);
var atxtarea = $A(txtarea).sort();
I think I should use the .detect or .any methods.
Frank
on 2008-06-30 15:00
on 2008-06-30 15:23
After sorting through the array, just loop through it and see if the next value equals the current value. Writing one FOR loop isn't going to kill you :)
on 2008-06-30 15:30
If you're in that much of a pinch, there's always:
if (my_array.length == my_array.uniq().length) { ... }
On Mon, Jun 30, 2008 at 8:22 AM, Diodeus <diodeus@gmail.com> wrote:
>
> After sorting through the array, just loop through it and see if the
> next value equals the current value.
>
> Writing one FOR loop isn't going to kill you :)
--
Science answers questions; philosophy questions answers.
on 2008-06-30 20:26
It's not complicated at all. Take a look at http://github.com/kangax/protolicious/tree/master/... -- kangax
on 2008-07-01 14:46
I have tried your suggestion. I am retrieved data from a <textarea>
form element with these values:
1111
2222
3333
1111
4444
My code that I have been testing using Firefox 3 and Firebug 1.0b4 is:
var txtarea = $F('txtarea4').split(/[\n\r]+/);
var atxtarea = $A(txtarea).sort();
Array.prototype.isUnique = function(value) {
var idx = this.indexOf(value);
return this.indexOf(value, idx + 1 == -1);
};
for (i=0; i<=atxtarea.length; i++) {
alert(atxtarea[i]);
atxtarea.isUnique(atxtarea[i]);
}
The 'alert' shows an 'undefined' value at the end of the loop. I am
receiving a -1 after the loop.
I have tried to setup the test using:
[1111,2222,3333,1111,4444].isUnique(1111) and get a 0 in return
(assume this is the index value of 1111) and not a -1 as I would
expect.
Can you provide me some additional assistance??
on 2008-07-01 16:12
You changed the method, so it doesn't work. The last line should be: this.indexOf(value, idx + 1) == -1; ... [1,2,3,1,2].isUnique(1); // false [1,2,3,1,2].isUnique(3); // true -- kangax
on 2008-07-01 16:17
Just discovered the mistake, but, I get 'true' with the '1111' value twice in the list or once in the list. Frank
on 2008-07-01 21:07
FYI,
Here is the code that I finally ended up with:
function chkdupes() {
var txtarea = $F('txtarea4').split(/[\n\r]+/);
var atxtarea = $A(txtarea).sort();
for (i=0; i<=atxtarea.length-1; i++) {
var idx = i+1;
if (atxtarea[i] == atxtarea[idx]) { alert('Duplicate value = ' +
atxtarea[i]);
var dupval = atxtarea[i];
var farea = atxtarea.join('\n');
$('txtarea4').value = farea;
$('txtarea4').focus();
};
}
}
It works as I intended. I also want to code a set focus on the element
that was reported to be the duplication item.
Frank