0

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.

2
  • 8
    An array has keys that are numerical and ordered, not strings. If you want those, use an object instead. Commented Apr 30, 2017 at 18:21
  • I'm pretty sure Riyas is a PHP programmer. There are no associative array in JavaScript... :D Commented Apr 30, 2017 at 18:33

1 Answer 1

2

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).

Sign up to request clarification or add additional context in comments.

3 Comments

i think array.k2 will be undefined! array will be empty
@PriyeshKumar — You think wrong! jsbin.com/dovilom/1/edit?js,console
ohh, I was checking array.item :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.