473,779 Members | 1,873 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

i need an equivalent to PHP's array_unique function


The PHP scripting language has the array_unique() function that gets
the unique, non-redundant values out of an array.

Does Javascript have anything similar?

Jul 23 '05 #1
7 6495
Jc
lk******@geocit ies.com wrote:
The PHP scripting language has the array_unique() function that gets
the unique, non-redundant values out of an array.

Does Javascript have anything similar?


The short answer is no, but there's a few ways around it.

If you use an Object as a pretend associative array you can either
iterate once through the array and put each element into the
associative array and get a unique list (but it won't be guaranteed to
be in the same order as the indexed array, using the for..in
statement). You could also just use an "associativ e array" to start
with, instead of an array.

If you care about order, you could add the data to both an associative
array and the indexed array, and use the associative array to quickly
check if the data already exists before adding it to the arrays.

Jul 23 '05 #2
Jc wrote:
lk******@geocit ies.com wrote:
The PHP scripting language has the array_unique() function that gets
the unique, non-redundant values out of an array.

Does Javascript have anything similar?

The short answer is no, but there's a few ways around it.

If you use an Object as a pretend associative array you can either
iterate once through the array and put each element into the
associative array and get a unique list (but it won't be guaranteed to
be in the same order as the indexed array, using the for..in
statement). You could also just use an "associativ e array" to start
with, instead of an array.


The only problem being that JS has no "associativ e arrays".

--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Jul 23 '05 #3
Jc
Randy Webb wrote:
Jc wrote:
If you use an Object as a pretend associative array you can either
iterate once through the array and put each element into the
associative array and get a unique list (but it won't be guaranteed to
be in the same order as the indexed array, using the for..in
statement). You could also just use an "associativ e array" to start
with, instead of an array.


The only problem being that JS has no "associativ e arrays".


I agree that JS does not explicitly implement a data structure called
an "associativ e array". However, being such an expressive language, JS
objects can definitely be used as a collection of name/value pairs,
which I don't have a problem referring to informally as an associative
array. Not to mention that this is significantly more meaningful to
someone coming from a PHP background.

I thought it was obvious that in my previous post I was referring to a
feature in JS which is commonly referred to as an "associativ e array"
for simplicity in explanations. Notice how I said "pretend", and notice
I quoted the words "associativ e arrays", and notice how I said to use a
JS object, which is how JS implements what is known as an associative
array in other languages.

Just to clarify things, when I referred to using a JS object as a
pretend associative array, I was referring to the technique described
on the following site (someone may have a better link):

http://www.unix.org.ua/orelly/web/jscript/ch07_06.html

FYI: An interesting application of JS objects used in this way (in
combination with an initialization syntax/notation) is JSON:

http://www.crockford.com/JSON/index.html

Jul 23 '05 #4
<lk******@geoci ties.com> wrote in message news:11******** **************@ g14g2000cwa.goo glegroups.com.. .

The PHP scripting language has the array_unique() function that gets
the unique, non-redundant values out of an array.

Does Javascript have anything similar?


I think these functions will do what you want.

..arrayUnique() returns a new array containing the unique values,

..trashDuplicat es() acts upon the original array, returning it with duplicates removed.
For strict type-comparisons, remove the comments in the 'if' statement.

<SCRIPT type='text/javascript'>

var dups=["1", 1, "four", "3", 2, "2", 1, "four", "2", 2, 3, "3",2];

if( typeof Array().arrayUn ique=='undefine d' )
Array.prototype .arrayUnique=fu nction()
{
var noDuplicates=[];

for( var i=0, k=0; i<this.length; i++ )
{
for( var j=0; j<noDuplicates. length && this[i]!=noDuplicates[j] ; j++ )
;
if(j==noDuplica tes.length)
noDuplicates[k++]=this[i];
}

return noDuplicates;
}
if( typeof Array().trashDu plicates=='unde fined' ) // as if...
Array.prototype .trashDuplicate s=function()
{
for( var i=0; i<this.length; i++ )
for( var j=0; j<this.length; j++ )
if( i!=j && this[i]==this[j] /** && typeof(this[i])==typeof(this[j]) **/ )
for( var k=j; k<this.length; k++ )
{
this[k]=this[k+1];
this.length--;
} // no .splice() in I.E. 5.0 :(

return this;
}

alert("dups.arr ayUnique()==[ "+dups.arrayUni que() +" ]\n\ndups.trashD uplicates()==["
+dups.trashDupl icates()+"] New length is: "+dups.leng th);

</SCRIPT>

--
Stephen Chalmers http://makeashorterlink.com/?H3E82245A

547265617375726 520627572696564 206174204F2E532 E207265663A2054 51323437393134

Jul 23 '05 #5
fox


lk******@geocit ies.com wrote:
The PHP scripting language has the array_unique() function that gets
the unique, non-redundant values out of an array.

Does Javascript have anything similar?


works with indexed, associative, and "mixed" arrays:
Array.prototype .unique = function()
{

var mark = [];

for(var i in this)
{

// var indx = this[i]; --> if type does not matter
// create a unique index if type does matter
var indx = this[i] + "_" + typeof(this[i]);

if(mark[indx])
delete this[i];
else
mark[indx] = this[i];
}

this.sort();

// empty indexed entries are at the end of the array
// shorten it [delete does not reduce array]

while(!this[this.length-1]) this.length--;

}
var dups = ["1", 1, "four", "3", "2", 2, 1, "four", "2", 2, 3, "3"];

dups["quick"] = 44;
dups["brown"] = "test";
dups["fox"] = 44;
dups["jumps"] = "test";

dups.unique();

dups is changed -- no need to create a new array to receive a result.

resultant array is sorted (hope that doesn't matter)

result of dups.unique():

slot : value type
0 : 1 --> number
1 : 1 --> string
2 : 2 --> number
3 : 2 --> string
4 : 3 --> number
5 : 3 --> number
6 : four --> string
quick: 44 --> number
brown: test --> string
result if type doesn't matter:

0 : 1
1 : 2
2 : 3
3 : four
quick: 44
brown: test

Jul 23 '05 #6
fox
*** correction follows ***

<snip>


Array.prototype .unique = function()
{

var mark = [];

for(var i in this)
{

// var indx = this[i]; --> if type does not matter
// create a unique index if type does matter
var indx = this[i] + "_" + typeof(this[i]);

if(mark[indx])
delete this[i];
else
mark[indx] = this[i];
}

this.sort();

// empty indexed entries are at the end of the array
// shorten it [delete does not reduce array]

if(this.length) {
while(!this[this.length-1]) this.length--; }
}

[**IE did not start generating errors until it was restarted]
Jul 23 '05 #7
"Jc" <go****@weinric hs.com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .
lk******@geocit ies.com wrote:
The PHP scripting language has the array_unique() function that gets
the unique, non-redundant values out of an array.

Does Javascript have anything similar?


The short answer is no, but there's a few ways around it.

If you use an Object as a pretend associative array you can either
iterate once through the array and put each element into the
associative array and get a unique list (but it won't be guaranteed to
be in the same order as the indexed array, using the for..in
statement). You could also just use an "associativ e array" to start
with, instead of an array.

If you care about order, you could add the data to both an associative
array and the indexed array, and use the associative array to quickly
check if the data already exists before adding it to the arrays.


He can implement something that works very similar to PHP's
array_unique() quite easily:

<script type="text/javascript">
// modifies the current Array
function array_unique(ar r) {
var existingItems = {};
var prefix = String(Math.ran dom() * 9e9);
var ii = 0;
while (ii < arr.length) {
if (existingItems[prefix + arr[ii]]) {
arr.splice(ii, 1);
} else {
existingItems[prefix + arr[ii]] = true;
++ii;
}
}
}
// returns a copy
function array_unique2(a rr) {
var newArray = [];
var existingItems = {};
var prefix = String(Math.ran dom() * 9e9);
for (var ii = 0; ii < arr.length; ++ii) {
if (!existingItems[prefix + arr[ii]]) {
newArray.push(a rr[ii]);
existingItems[prefix + arr[ii]] = true;
}
}
return newArray;
}

var a = [ 'one', 'two', 'three', 'two', 'one' ];
alert(array_uni que2(a));
array_unique(a) ;
alert(a);
</script>

--
Grant Wagner <gw*****@agrico reunited.com>
comp.lang.javas cript FAQ - http://jibbering.com/faq
Jul 23 '05 #8

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

Similar topics

4
6351
by: MegaZone | last post by:
I'm having some issues with PHP DOMXML - in particular the get_elements_by_tagname method. Now, the PGP docs on this are, well, sparse, so maybe I'm just doing something stupid. I thought this method would behave like the 'findnodes' XML method in Perl. Namely that you can pass it an xpath statement and it will find nodes that match: $array = $node->get_elements_by_tagname($xpath); This is long so here's a pagebreak: And, indeed,...
3
50363
by: Phil Powell | last post by:
<?php class SuperClass { var $mySuperClassVar; function SuperClass($myVar) { $this->mySuperClassVar = $myVar; echo "super class var = $myVar<p>"; }
7
2549
by: am_ggh | last post by:
Is there a PHP equivalent of TCL's "upvar" ? I will appreciate any insights. Andy
2
4023
by: Adam Kubica | last post by:
Hellou. Anybody know about code that work equivalent to gzinflate() function used in PHP? I search via google but I don't found anything sensible :-(
18
15928
by: Csaba Gabor | last post by:
Is there a straightforward way of implementing a PHP equivalent to window.setTimeout? In a javascript web app, it's often the case that things are done on an event driven basis. For example, html elements might have things like onclick="buttonClicked()" to indicate that the function buttonClicked should be run when that element is clicked. The analogue can be done in PHP (on Windows) using com_event_sink. In other words, you can...
5
3005
by: GuangXiN | last post by:
I need an stmp client to send email through my mail server. I don't want to use php's mail function. who can recommend some?
2
1453
by: freddukes | last post by:
Okay... I'm a PHP noob but I have a good background in C++ and Python... Now all I want to do is iterate through the following file, and appending all products to an array, with information stored inside the array for each product, then return it... here is the file: // ../docs/products.txt // This document is for displaying all your products // To do this, there is a special format to create each offer. // The format is as follows:...
1
1683
by: divyac | last post by:
Hi I have a text file named email.txt which has the following contents test@test.com a@x.com zooman@deeply.bored.org b@x.com guess.me@where.ami.net testmore@test.com I want only the domain part of the listed email ids separately. The code which I tried is as follows
0
9632
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
9471
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10302
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
9925
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
7478
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
6723
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5372
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5501
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2867
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.