469,343 Members | 5,377 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,343 developers. It's quick & easy.

Javascript Array, Splice

So currently i have an application i developed some time ago that has 2 arrays...

this application randomly goes through the arrays displaying the names as it goes and finally stops on one (its a prize drawing application we use to distribute prizes at company parties)

when a name gets drawn it clears that array value... if the random loop lands on any empty spot it starts over... the problem with this is, after many names have been cleared it starts to repeat itself so much it runs very slow....

So i have been looking for a way to delete the array value all together such as .splice however it isnt working for me so basically if this is my array

FirstName[0] = "Josh"
FirstName[1] = "Bob"
FirstName[2] = "Tim"
FirstName[3] = "Ashley"
FirstName[4] = "Frank"

and i say... FirstName.Splice(0,1)

Then the array would be like below...
FirstName[0] = "Bob"
FirstName[1] = "Tim"
FirstName[2] = "Ashley"
FirstName[3] = "Frank"

anyone know how i can achieve this?
Jan 25 '08 #1
3 3210
428 256MB
splice returns the item(s) that get removed, so you can select and remove the selected item from the array in the same statement.

You'd use something like this to deal random cards from a deck, for example, but it should work for your purpose.

Expand|Select|Wrap|Line Numbers
  1. var L=FirstName.length,f;
  2. while(--L){
  3.     f=FirstName.splice(Math.floor(Math.Random()*L),1);
  4. //write the name
  5. }
Jan 25 '08 #2
Well i need to remove the item from the array and then still be able to execute the same functions that search through the array. Ideally delete something then re-index the array with the data that still exists...
Jan 25 '08 #3
428 256MB
Then make an array of integers the length of your name list,
with each item a subsequent integer.
Shuffle the array and shift or pop your way through it,
using the integers returned as your name array indexes.

Expand|Select|Wrap|Line Numbers
  1. var L= FirstName.length;
  2. var i= 0,A=[];
  3. while(i<L) A[i]= i++;
  4. A.sort(function(){
  5.     return  .5 - Math.random();
  6. })
  7. while(A.length){
  8.     f= FirstName(A.pop());
  9.     //do whatever with f
  10. }
Jan 25 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

5 posts views Thread by effendi | last post: by
1 post views Thread by agendum97 | last post: by
18 posts views Thread by dhtml | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
1 post views Thread by Marylou17 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.