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?
-
check this stackoverflow.com/questions/281264/…Gaurang Dave– Gaurang Dave2018-02-06 00:47:52 +00:00Commented Feb 6, 2018 at 0:47
-
I don't understand what you are saying. Are you sure this is javascript?keithlee96– keithlee962018-02-06 00:48:12 +00:00Commented Feb 6, 2018 at 0:48
-
@keithlee96 I've added the console log screen.Lukas– Lukas2018-02-06 00:49:24 +00:00Commented Feb 6, 2018 at 0:49
-
@GaurangDave tried this, and just like above, none of them doesn't work :(Lukas– Lukas2018-02-06 00:49:57 +00:00Commented Feb 6, 2018 at 0:49
-
@Lukas Can you share the JS code (operation you are performing)?Gaurang Dave– Gaurang Dave2018-02-06 01:10:35 +00:00Commented Feb 6, 2018 at 1:10
Add a comment
|
1 Answer
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]
3 Comments
HMR
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);keithlee96
@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?
HMR
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)