I'm deleting some array object in traditional way: delete subDirectories[index]
. So, just after that this object is changing to [empty]
one. Now, how to filter that, undefined, bool, NaN
nothing works. I'm working with Vue.js and this contains an vuex
action. Can anybody help?
Asked
Active
Viewed 6,890 times
0

Lukas
- 7,384
- 20
- 72
- 127
-
check this https://stackoverflow.com/questions/281264/remove-empty-elements-from-an-array-in-javascript – Gaurang Dave Feb 06 '18 at 00:47
-
I don't understand what you are saying. Are you sure this is javascript? – keithlee96 Feb 06 '18 at 00:48
-
@keithlee96 I've added the console log screen. – Lukas Feb 06 '18 at 00:49
-
@GaurangDave tried this, and just like above, none of them doesn't work :( – Lukas Feb 06 '18 at 00:49
-
@Lukas Can you share the JS code (operation you are performing)? – Gaurang Dave Feb 06 '18 at 01:10
1 Answers
6
If you want to delete all null, undefined, (or any false-like) values in an array, you can just do:
var arr = [1,3,5, null, False];
var res = arr.filter(val=>val);
console.log(res); // [1,3,5]
Alternatively, you can explicitly remove null and undefined:
var res = arr.filter(val => (val!==undefined) && (val!==null));
console.log(res); // [1,3,5]

keithlee96
- 1,724
- 2
- 11
- 17
-
In this case; because element was removed with `delete` you have a value in the array called `empty`. If the value is `empty` the function in filter isn't called so you can do this: `arr.filter(x=>true);` Try this in console:`arr = [1,2,3];delete arr[1];arr.filter(x=>true);` – HMR Feb 06 '18 at 03:47
-
@HMR Huh, that works. That's way more elegant than my solution. I had no idea that empty was a thing in Javascript Arrays. So are empty cells always ignored by all array functions (filter, map, etc)? Is there a difference between empty and undefined? – keithlee96 Feb 06 '18 at 23:58
-
Empty is a special value, the array is `empty x 10) when doing `new Array(10)` Map isn't called when you do: `new Array(10).map(_=>console.log("hi"))` It's also not called when you delete: `var arr = [1,2,3];delete arr[0];arr.map(x=>{ console.log(x);return x; })` but the array returned still has a length of 3 and the empty item is still there. I try to avoid `delete` and use `new Array` like this: `Array.from(new Array(10),(x,index)=>index)` – HMR Feb 07 '18 at 04:33