Javascript: how to clear undefined values โ€‹โ€‹from an array

I am trying to loop through an array and delete and skip items until only one exists. I tried splicing, but it mixed up my loop because the element from arr [1] then becomes arr [0], etc.

Let's say there are 10 people. I would like to remove person 1, then save person 2, then delete person 3 and save person 4. This pattern will continue until only one remains.

any help would help.

+4
source share
13 answers

you should not change the collection during iteration, not just JavaScript, but the whole language, define a new array and add the ones you want to delete in it, and repeat it later to remove it from the first.

+9
source

Filter out the false elements:

var a=[1,2,"b",0,{},"",NaN,3,undefined,null,5]; var b=a.filter(Boolean); // [1,2,"b",{},3,5] 
+26
source

When you splicing, just decrease your loop index.

There were many good suggestions, I will send the code for different parameters, and you can decide what to use

Splice Reduction Index http://jsfiddle.net/mendesjuan/aFvVh/

 var undef; var arr = [1,2, undef, 3, 4, undef]; for (var i=0; i < arr.length; i++) { if ( arr[i] === undef ) { arr.splice(i,1); i--; } } 

Loop back http://jsfiddle.net/mendesjuan/aFvVh/1/

 var undef; var arr = [1,2, undef, 3, 4, undef]; for (var i=arr.length - 1; i >=0; i--) { if ( arr[i] === undef ) { arr.splice(i,1); } } 

Copy to new array http://jsfiddle.net/mendesjuan/aFvVh/2/

 var undef; var arr = [1,2, undef, 3, 4, undef]; var temp = []; for (var i=0; i < arr.length; i++) { if ( arr[i] !== undef ) { temp.push(arr[i]) } } arr = temp; 

Use a filter , which is just a fancy way to create a new array.

 var undef; var arr = [1,2, undef, 3, 4, undef]; arr = arr.filter(function(item){ return item !== undef; }); 

At the end of all these examples, arr will be [1,2,3,4]

Performance

IE 11, FF, and Chrome agree that Array.splice is the fastest. 10 times (Chrome), 20 times (IE 11) with Array.filter. precision Array.filter. Putting elements into a new array was also slow compared to Array.slice . See http://jsperf.com/clean-undefined-values-from-array2

I am really surprised to see that IE leads the package here, and to see Chrome behind FF and IE. I donโ€™t think I have ever done a test with this result.

+6
source

Cycle back. (Thus, deleting elements will not affect the indices of elements that have not yet been processed.)

+3
source

If you accidentally use CoffeeScript , then to remove undefined from the array, do

 values = ['one', undefined] values = (item for item in values when item != undefined) values /* => ['one'] */ 
+3
source

Surprisingly, no one answered the best and right way:

  • Create new array
  • Iterate over the old array and only click the elements you want to keep in the new array

some credit goes to comment @nnnnnn

+1
source

Not collecting exactly what you are trying to achieve, but I feel that you are relying on the position index of the element in the array to continue your program. In this case, I would suggest a hashed array, i.e. An array of Key <> Value pairs.

In this case, arr["2"] always points to the element that you originally placed in it. This way you can logically / numerically scroll without worrying about changes in position.

Beware of risk and type conversion errors!

0
source

It is best to duplicate the array and then merge with the original.

Or just use the collection (key-> value) and just delete the key, e.g.

  People = {a: "Person A", b: "Person B", c:"Person C"}; delete People.a; delete People.c; //now the People collection only has 1 entry. 

You can replace a, b, c with numbers, just using this as an example,

  People = {0: "Person A", 1: "Person B", 2:"Person C"}; delete People[0]; delete People[1]; 
0
source
 function removeUndefined(array) { var i = 0; while (i < array.length) if (typeof array[i] === 'undefined') array.splice(i, i); else i++; return array; } 

EDIT: I wrote this based on the title. The question seems to be asking something completely different.

0
source

this is a sample for you

 <script lanauge = "javascript"> var arr = ["1","2","3","4"]; delete arr[1];// arr[1] is undefined delete arr[2];// arr[2] is undefined // now arr.length is 4 var todelete = []; for (i = 0 ; i < arr.length ;i++) { if (typeof arr[i] == 'undefined') todelete.push(i); } todelete.sort(function(a, b) { return ba }); // make the indeies from big to small for (i = 0;i < todelete.length; i ++) { arr.splice(todelete[i],1); } // now arr.length is 2 </script> 
0
source

This may not be what you want, but you can easily figure out what the final element will be at the end of this procedure, and then just grab it. Assuming the elements of the array are contiguous and start with arr [0], you can find:

 var logBase2OfLength = Math.floor(Math.log(arr.length) / Math.log(2)); var finalElement = arr[(1 << logBase2OfLength) - 1]; 

Basically, if you take the integer power 2, which is less than or equal to the number of elements in your array, this is the position of the element that will remain after the entire cycle and deletion.

0
source
 >If you are getting undefined during deletion of the key-pair, Then to prevent "undefined" you can try code given below to delete key-pair 1) test = ["1","2","3","4",""," "]; 2) var delete = JSON.stringify(test); case1) delete = delete.replace(/\,""/g,''); or case2) delete = delete.replace(/\," "/g,''); or case3) delete = delete.replace(/\,null/g,''); 3) var result = JSON.parse(delete); 
0
source
  while(yourarray.length>1) //only one left { // your code } 
-1
source

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


All Articles