Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's an easy way of storing an array of numbers in Javascript that I can add/remove from?

Tags:

javascript

In C# I would create a List then I could add and remove numbers very easily. Does identical functionality exist in Javascript, or do I have to write my own methods to search and remove items using a loop?

var NumberList = [];

NumberList.Add(17);
NumberList.Add(25);
NumberList.Remove(17);

etc.

I know I can use .push to add a number, so I guess it's really how to remove an individual number without using a loop that I'm looking for.

edit: of course, if there's no other way then I'll use a loop!:)

like image 489
NibblyPig Avatar asked Nov 28 '25 03:11

NibblyPig


2 Answers

The Array objet has this kind of method :

var myArray = new Array();
myArray.push(12);
myArray.push(10);
myArray.pop();

All detail can be found here

To remove a specific value , some tricks are possible :

var id = myArray.indexOf(10); // Find the index
if(id!=-1) myArray.splice(id, 1);
like image 195
grunk Avatar answered Nov 29 '25 18:11

grunk


You have to use splice and indexOf if you know that there is only one copy of the value that you want to remove and if there can be many copies then you have to use splice in a loop.

If you're using Underscore.js then you can use:

array = _.without(array, 17);
like image 33
rsp Avatar answered Nov 29 '25 16:11

rsp