Solved

how to reindex the array

Posted on 1998-09-11
4
1,537 Views
Last Modified: 2012-08-14
Is there a way to repack the index once you delete an
element of the array. This leads to a ever growing array
since my application is adding and deleting
elements of the array. Without repack, there will be holes
in the array.
0
Comment
Question by:trinh
  • 2
  • 2
4 Comments
 
LVL 28

Expert Comment

by:sybe
ID: 1270763
array.sort()

will reindex the array. You can define your own compare function

array.sort(myFunction)

function myFunction(a,b) {
  return a-b;
}
0
 

Author Comment

by:trinh
ID: 1270764
No sort won't reindex the array. I try it and still get the error.
after deleting an element of the array, I sort the array then go through
the loop to display the array contents, an error occurs when it reaches the
empty array element that has just been deleted. (error is:
myarray[...].element is not an object). Mind you I am using 2 dimentional array
0
 
LVL 28

Accepted Solution

by:
sybe earned 30 total points
ID: 1270765
Hmm, I worked with a 1 dimensional array, and solved something comparable by sorting the array in such a way that (aftere each "delete") the empty element was the last one, then copying all elements except the last one to a temporary array and then copying the temporary array back to the original. Bit ugly, but it works.

0
 

Author Comment

by:trinh
ID: 1270766
I can see your trick, certainly it will work but for a large 2 dimentional array it is
a bit ugly. By the way, how do you sort the array to make sure that the deleted
element will always be the last one ?
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

In this article, we'll look how to sort an Array in JavaScript, including the more advanced techniques of sorting a collection of records either ascending or descending on two or more fields. Basic Sorting of Arrays First, let's look at the …
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now