Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing elements from JavaScript arrays

Tags:

javascript

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.

like image 256
tonyf Avatar asked Nov 26 '22 21:11

tonyf


1 Answers

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"]
like image 129
gnarf Avatar answered Jan 03 '23 02:01

gnarf