Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1818
  • Last Modified:

how to reindex the array

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
trinh
Asked:
trinh
  • 2
  • 2
1 Solution
 
sybeCommented:
array.sort()

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

array.sort(myFunction)

function myFunction(a,b) {
  return a-b;
}
0
 
trinhAuthor Commented:
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
 
sybeCommented:
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
 
trinhAuthor Commented:
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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now