Naran Hirani <N.******@hgmp.mrc.ac.uk> writes:
I am collecting a set of values from a web form and putting them into
a JS array object.
I now want to check/ensure that there or no repeated values in this
array. I can think of many ways to do this using one or many loops
but was just wondering if there was
any other clever way of doing this using string functions or the
RegExp object perhaps.
That is sadly a problem that is not solvable by regular expressions [1].
Needless to say I am a JS virgin so any help or advice would be much
appreciated.
What you can do is to create the elements as properties of an object,
and then check whether you try to create the same property twice.
This function should check an array for duplicate entries (it expects
the entries to be strings, otherwise they are converted to strings
before comparing).
function containsDoubles(array) {
var object = {};
for (var i in array) {
if (object[array[i]]) {
return true;
}
object[array[i]] = true;
}
return false;
}
You could also make this check while adding the elements to the array,
but I doubt the change in efficiency is worth it.
/L
[1] Perl's regular expressions might work, since they extend their
RegExps with features that are not regular, but it will not be efficient.
--
Lasse Reichstein Nielsen -
lr*@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
'Faith without judgement merely degrades the spirit divine.'