Creating an array using another array in javascript

I have an array in which I added 3 data in different indices as shown 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 extract a value from an array and add it to another array. is there any simplest way i can use it. Until now, I am taking a value using the "for" loop, it is normal when I have a small amount of data. here I need only 3 values, but the loop runs for 6 times.

Thank you in advance

+4
source share
5 answers

The filter function is what you need.

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

"".

, :

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

:

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

:

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

:

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

:

[4,7,8]
0

, , , , undefined. , .

, undefined, , , 2 , undefined, . , HashMap Array.

javascript, , :

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
}
0

You can 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 in how you declare 'a': a = {}, not a = [].

0
source

Source: https://habr.com/ru/post/1527851/


All Articles