tags:

views:

698

answers:

3

Hi,

I have the following array setup, i,e:

var myArray = new Array();

Using this array, I am creating a breadcrumb menu dynamically as the user adds more menu items. I am also allowing them to removing specific breadcrumb menu items by clicking on the cross alongside eatch breadcrumb menu item.

Array may hold the following data:

myArray[0] = 'MenuA';
myArray[1] = 'MenuB';
myArray[2] = 'MenuC';
myArray[3] = 'MenuD';
myArray[4] = 'MenuE';

My questions are:

a) In javascript, how can I remove element [1] from myArray and then recalculate indexes or is this not possible?

b) If I don't want menu option MenuB, do I need to splice it to remove it?

My problem is, if the user removes menu items as well as create news one at the end, how will the indexes to these elements be spreadout?

I just want to be able to remove items but don't know how the array indexes are handled.

Thanks. Tony.

+2  A: 

http://www.w3schools.com/jsref/jsref%5Fsplice.asp

Splice should recalculate the correct indexes for future access.

phantombrain
+7  A: 

You could use myArray.push('MenuA'); so you don't specify direct numbers when adding elements.

To remove an element I.E. 'MenuB':

// another quick way to define an array
myArray = ['MenuA', 'MenuB', 'MenuC', 'MenuD', 'MenuE']; 

// remove an item by value:
myArray.splice(myArray.indexOf('MenuB'),1);

// push a new one on
myArray.push('MenuZ');

// myArray === ["MenuA", "MenuC", "MenuD", "MenuE", "MenuZ"]
gnarf
indexOf for arrays it not supported on IE. it can be prototyped -> http://stackoverflow.com/questions/1744310/how-to-fix-array-indexof-in-javascript-for-ie-browsers
vsync
if you use jQuery, it offers built-in indexOf for arrays -> http://api.jquery.com/jQuery.inArray/
vsync
+9  A: 

I like this implementation of Array.remove, it basically abstracts the use of the splice function:

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

Usage:

// Remove the second item from the array
array.remove(1);
// Remove the second-to-last item from the array
array.remove(-2);
// Remove the second and third items from the array
array.remove(1,2);
// Remove the last and second-to-last items from the array
array.remove(-2,-1);
CMS
Thanks CMS and to the rest who replied.
tonsils
@CMS: could you explian me more, plz? I don't undertand why not just using the simple splice native method to remove elements from an array.
Marco Demajo