By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,089 Members | 2,191 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,089 IT Pros & Developers. It's quick & easy.

Javascript Array, Splice

P: 6
So currently i have an application i developed some time ago that has 2 arrays...
FirstName
LastName

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
Share this Question
Share on Google+
3 Replies


100+
P: 428
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. }
  6.  
Jan 25 '08 #2

P: 6
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

100+
P: 428
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. }
  11.  
Jan 25 '08 #4

Post your reply

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