Riyas
Riyas

Reputation: 327

How to remove an element from a javascript array

I have an array as below

var array = [];

var item1 = 'k1';
var itemvalue1 = {'key1':'value1'};
array[item1] = itemvalue1;

var item2 = 'k2';
var itemvalue2 = {'key2':'value2'};
array[item2] = itemvalue2;

Two questions...

  1. How to get the position(index) of the item2 in the array
  2. How to remove the item item2 from the array

Any help is appreciated.

Upvotes: 0

Views: 1247

Answers (1)

Quentin
Quentin

Reputation: 943214

How to get the position(index) of the item2 in the array

It doesn't have one.

You assigned the value to a property called k2. That isn't a numeric index, so it doesn't have a position.

You almost certainly should be using a plain object ({}) and not an array in the first place.

How to remove the item item2 from the array

delete array.k2

(as per this question).

Upvotes: 2

Related Questions