0

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?

enter image description here

Lukas
  • 7,384
  • 20
  • 72
  • 127

1 Answers1

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