user3326265
user3326265

Reputation: 257

Creating array using another array in javascript

I am having an array in which i have added 3 data in different index, as below

  var a=[];
   a[1]=4;
   a[3]=7;
   a[4]=8;

now my array will look like this

 a=[undefined, 4, undefined, 7, 8, undefined]

i want to take the value alone from the array and need to add in another array. is there any simplest way, that i can make use of it. Till now i am taking the value using "for" loop, it is ok when i have small number of data. here i need only 3 values, but the loop execute for 6 time.

Thanks in advance

Upvotes: 4

Views: 94

Answers (5)

Yair Nevet
Yair Nevet

Reputation: 13003

The raw array:

var originalArr = [];
a[1] = 4;
a[3] = 7;
a[4] = 8;

The filter logic:

function filterUndefined(originalArr){
    var valuesArray = [];
    for(var i = 0; i < originalArr.length; i++){
        if(originalArr[i] !== undefined){
          valuesArray.push(a[i]);
        }
        return valuesArray;
    }
}

Result:

[4,7,8]

Upvotes: 0

Mehran Hatami
Mehran Hatami

Reputation: 12961

The point is, whenever you set an index in an array whereas the other previous indexes are not there, your array add them with undefined values. If you have a huge amount of data in this array it is not a good practice.

You can use filter to actually filter the undefined values but the point is, when the array has a huge amount of data, what you do is creating 2 array which the first array has lots of indexes with undefined values, which is not a good practice. I believe it is more of a HashMap instead of Array.

if I where you I would use javascript object instead, and to loop through it like an array, you can do:

var a={};
a[1]=4;
a[3]=7;
a[4]=8;
var keys = Object.keys(a);
for(var i=0;i<keys.length;i++){
    var value = a[keys[i]];
    //do whatever you want
}

Upvotes: 0

MarzSocks
MarzSocks

Reputation: 4318

You could consider a 'key/value' object instead of an array.

> var a={}; 
> a[1]=4; 
> a[3]=7; 
> a[4]=8;

Note that the difference is the way you declare 'a': a={} rather than a=[].

Upvotes: 0

Jim Jeffries
Jim Jeffries

Reputation: 10081

The filter function is what you are after.

var newArray = a.filter(function(item) {
  return item !== undefined;
});

Upvotes: 1

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276296

Most array methods skip over "holes" anyway.

If you don't explicitly want to filter them out, just call an array method on them:

var arr = a.filter(function(){return true});

Or shorthand:

[,4,,7,8].filter(function(){ return true}); // [4, 7, 8]

Upvotes: 4

Related Questions