473,767 Members | 2,284 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

test for uniqueness problem

Hi Guys and Gals,

Please can u help me with this little problem.

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.

Needless to say I am a JS virgin so any help or advice would be much
appreciated.

Regards.
Naran Hirani

Jul 20 '05 #1
6 3903
> 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.


Don't use an array, use an object. Use the values as the keys of the object.
Then use for..in to extract the keys.

var o = {};
... some process that produces values ...
o[value] = true;
}
for (value in o) {
if (value === true) {
... value is unique ...
}
}

http://www.crockford.com/#javascript
Jul 20 '05 #2
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.'
Jul 20 '05 #3
Thanks Douglas, and Lasse for your replies and code fragments.
I was all set to tackle this problem using arrays, but after your
warning and suggestions
I will implement something along the lines you guys are suggesting.

Regards,
Naran.
Douglas Crockford wrote:
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.


Don't use an array, use an object. Use the values as the keys of the object.
Then use for..in to extract the keys.

var o = {};
... some process that produces values ...
o[value] = true;
}
for (value in o) {
if (value === true) {
... value is unique ...
}
}

http://www.crockford.com/#javascript


Jul 20 '05 #4
"Lasse Reichstein Nielsen" <lr*@hotpop.com > wrote in message
news:d6******** **@hotpop.com.. .
<snip>
function containsDoubles (array) {
var object = {};
for (var i in array) {
if (object[array[i]]) {
return true;
}
object[array[i]] = true;
}
return false;
}


I was recently bitten while trying this. Somehow the string
'constructor' found its way into the data and of course
object.construc tor is always true. I ended up having to explicitly
prefix all of the data strings with 'Q_' to safely be able to use them
as Object property names without risking conflicts with existing
JavaScript Object properties.

Richard.
Jul 20 '05 #5
"Richard Cornford" <Ri*****@litote s.demon.co.uk> writes:
I was recently bitten while trying this. Somehow the string
'constructor' found its way into the data and of course
object.construc tor is always true. I ended up having to explicitly
prefix all of the data strings with 'Q_' to safely be able to use them
as Object property names without risking conflicts with existing
JavaScript Object properties.


Good point! The apparently empty object ... isn't.
You could also prefix with " " (space), but "Q_" is probably safe enough.

/L
--
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.'
Jul 20 '05 #6
"Lasse Reichstein Nielsen" <lr*@hotpop.com > wrote in message
news:u1******** **@hotpop.com.. .
<snip>
You could also prefix with " " (space), but "Q_" is
probably safe enough.


That is a good suggestion, I was thinking in terms of legal JavaScript
identifiers and looking for an identifier prefix that would be
improbable. A space character is not only improbable but actually
impossible in dot notation, and in the context of a square bracket
reference its legality as an identifier is not significant.

It might make the code less easy to comprehend, being superficially
mistakable for - ""+stringVa r; - as a method to force type conversion to
a string, but an appropriate comment should sort that out.

Richard.
Jul 20 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2972
by: Puvendran Selvaratnam | last post by:
Hi, First of all my apologies if you have seen this mail already but I am re-sending as there were some initial problems. This query is related to defining indexes to be unique or not and consequences thereof. Some documented facts that I am aware of include
1
1273
by: Karsten Hilbert | last post by:
There recently was a discussion on how to enforce uniqueness on a row for a given condition, say allow many address rows for a person where active = false but only one where active = true. I cannot find it in the archives. Can someone please point me to the messages so I can read up ? Thanks. Also I can't find the relevant section in Celko's SQL for Smarties anymore :-(( I know it's in there, I did see it before... I am trying to do...
6
2500
by: Andreas | last post by:
Hello list, what about uniqueness of inherited primary keys ? eg you have : create table objects ( id int4, date_created timestamp(0), primary key (id)
2
2164
by: Dirk Declercq | last post by:
Hi, Is it possible in Xml to enfore the uniqueness of an element based on his attribute value. Say I have this schema : <?xml version="1.0" encoding="UTF-8"?> <xs:schema targetNamespace="http://www.egemin.com/Epia/StringResources" xmlns:xs="http://www.w3.org/2001/XMLSchema"
1
1565
by: Mr. Almenares | last post by:
Hello: I’m trying to do a schema with recurrent structure for a Book like a Node can have many Nodes inside or One leave. So, the leaves have an attribute that is Identifier. My goal is define Uniqueness that guarantees to the attribute Identifier his uniqueness. That I don’t know the depth of levels I have to put in the xpath attribute of the selector something like this TOC/descendant::Tree/Data, but this is not allow. How I can...
1
1584
by: MDS | last post by:
All, I am endeavouring to implement an "Also in the area" feature to an Access 97 DB. Within the table, there are two columns drawn from the same domain - let's call them Place A and Place B. Place A and Place B form the composite primary key. When the user enters "Place A" is in the area of "Place B," it should
0
1142
by: RICHARD BROMBERG | last post by:
I am writing an Access 2000 program for scoring an athletic tournament. I have a Members table (tblMembers) that contains Member information like Name, Address, Member Number. Member Number is unique and is the Primary Key. I also have a Competitors table (tblCompetitors) . It contains a Competitor Number and Member Number. Competitor Number is unique and is the primary key
0
2932
by: Matthew Wieder | last post by:
I have the following requirement: A form with 2 ListViews. lvSource which contains a list of items that the user can select from and lvTarget where the selected item(s) end up. Items should never be removed from lvSource, yet no item can be added to lvTarget more then once. To ensure the last requirement I set the .Name property on each ListViewItem as it is created in lvSource to be that entity's unique ID. Then I call...
5
2587
by: Alan Little | last post by:
I have affiliates submitting batches of anywhere from 10 to several hundred orders. Each order in the batch must include an order ID, originated by the affiliate, which must be unique across all orders in all batches ever submitted by that affiliate. I'm trying to figure out the most efficient way to check the uniqueness of the order ID. Order data is being submitted to Zen Cart, and also stored in custom tables. I have created a unique...
0
9571
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10168
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10009
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9959
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9838
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7381
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3929
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2806
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.