Keyur Shah
Keyur Shah

Reputation: 536

JavaScript Array creates empty element

var arr = [];
console.log(arr);
console.log("Length: " + arr.length);
arr[1] = [{},{}];
console.log(arr);
console.log("Length: " + arr.length);
arr[3] = [{},{}];
console.log(arr);
console.log("Length: " + arr.length);

So when I create an array like above it gives empty/undefined elements in between.

I want to remove those empty/undefined elements while preserving the index values.

vm.eArray = vm.eArray.filter(function (arr) {
    return arr.length;
});

I'm using the above code to remove the undefined elements but it messes my index/key values.

Or is there any way to avoid it at first place?

Upvotes: 0

Views: 99

Answers (4)

Devin
Devin

Reputation: 134

I would just use an object to store your values.

    var arr = {};
    console.log(arr);
    console.log("Length: " + Object.keys(arr).length);
    arr[1] = [{},{}];
    console.log(arr);
    console.log("Length: " + Object.keys(arr).length);
    arr[3] = [{},{}];
    console.log(arr);
    console.log("Length: " + Object.keys(arr).length);

    for (something in arr){
      console.log(arr[something]);
    }

Upvotes: 1

edkeveked
edkeveked

Reputation: 18381

Array are an index data structure. So when using them, it is better to keep that structure otherwise there is no use to use an array. For your use case, you can use whether a Map(), or an array of Json element.

  • Using a Map, your indexes (1, 2, 3) can become directly the keys of your array.
  • Another solution could be to use an array of Json element, where each element has a key and a value

var myMap = new Map();
//to add the element with index 1
myMap.set(1, [{},{}]);

//to add the element with index 3
myMap.set(3, [{},{}]);

// you can iterate over them if you want like an array
console.log("with a map")
myMap.forEach((key, value) => console.log(key, value));

// using a Json object

var myObject = [];
myObject.push({id: 1, value:[{},{}]})
myObject.push({id: 3, value:[{},{}]})

//iterate over it, because it is still an array, but of Json element
console.log("with array of json")
for (element of myObject){
  console.log(element.id, element.value)
}

Upvotes: 2

Omaim
Omaim

Reputation: 234

var arr = new Map();
console.log(arr);
console.log("Length: " + arr.size);
arr.set(1,[{},{}]);
console.log(arr);
console.log("Length: " + arr.size);
arr.set(3,[{},{}]);
console.log(arr);
console.log("Length: " + arr.size);

You can use Map(), and get the size using map.size.

Upvotes: 2

Madhavan.V
Madhavan.V

Reputation: 845

You are assigning value arr[1] = arr[1] = [{},{}]; at index 1. So you are skipping index 0. By default, javascript will place undefined there.

Upvotes: 0

Related Questions