var a = new array();
a[1] = 'A';
b[10] = 'B';
console.log(a);
/*[undefined, "A", undefined, undefined, undefined, undefined, undefined, undefined,
  undefined, undefined, "B"]*/

I want to remove undefined element but what is the process??

share|improve this question
feedback

4 Answers

up vote 5 down vote accepted

First of all, jQuery has nothing to do with this.

Second, arrays are "autofilled". If you define index 10, all indexes 0 - 9 will be occupied automatically, that's just the way Javascript arrays work.

What you're looking for is probably an object:

var a = {};
a[1] = 'A';
a[10] = 'B';

or

var a = {
    1 : 'A',
    10 : 'B'
};
share|improve this answer
but i have need a list of value – Hasan Aug 4 '10 at 6:41
feedback

well, to remove those undefined parts do

a[0] = 'A';
a[1] = 'B';

In your snippet, you fill the element with index 10 which forces the ECMAscript to create an array with 10 fields. There are no definitions for all that fields between 1 and 10, which means those are correctly undefined.

To remove that fields you either have to set a proper value or map the non-undefined values into a new array which would just be unnecesarry if you create a correct array in the first place.

Create an true object instead of an array (which actually also is an object) to have your desired behavior.

var a = {};

a[1] = 'A';
a[2] = 'B';

console.log(a);
share|improve this answer
but i need index number as so i have done :( – Hasan Aug 4 '10 at 6:33
feedback

In this case you can use an Object instead of an Array like so:

var a = {}; // or var a = new Object();
a[1] = 'A';
a[10] = 'B';
a['foo'] = 'bar';
a.bar = 'foo'; // same as a['bar'] = 'foo';
console.log(a);
share|improve this answer
feedback

Arrays always start at 0 and then go up to the last filled index. You could use an object to solve your problem:

var a = {};
a[1] = 'A';
a[10] = 'B';
share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.