jofftiquez
jofftiquez

Reputation: 7708

Javascript remove item on array using splice() not working

So I have an array like this var arr = [foo1:"bar1", foo2:"bar", foo3:"bar3"].

Then I used this arr.splice(index, 1); given that the index is dynamic lets just say it's 0 but the value foo1:"bar1" wasn't removed from the array.

Also the above array works on my code but it shows an error on JSFiddle. I have no idea why.

Thanks.

EDIT I dont know why it doesn't show an error on my console but here's how I did it.

var arr = [];

I dynamically added value to the array by doing

arr["foo"] = "bar";

which resulted to [foo:"bar"];

Any idea guys?

EDIT 2

Here's the screenshot of the console. enter image description here

Upvotes: 1

Views: 1273

Answers (2)

Tân
Tân

Reputation: 1

Long way:

var arr = [];

var foo1 = {};
foo1['foo1'] = 'bar1';

var foo2 = {};
foo1['foo2'] = 'bar2';

arr.push(foo1);
arr.push(foo2);

alert(arr.length); // output: 2

var index = arr.indexOf(arr, foo1); // or var index = $.inArray(arr, foo1);
arr.splice(index, 1);

alert(arr.length) // output: 1

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68393

Structure of this array is not valid.

var arr = [foo1:"bar1", foo2:"bar", foo3:"bar3"];

An array will have comma-separated items within square braces [], not key values

If you want to have key values, then it should be Object with curly braces {}

var arr = {foo1:"bar1", foo2:"bar", foo3:"bar3"};

and if you want to remove first property from the arr, then do

var keys = Object.keys( arr );
delete arr[ keys[ 0 ] ];

For adding a key value,

arr[ "foo5" ] = "bar";

Upvotes: 3

Related Questions