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

5
  • check this stackoverflow.com/questions/281264/… Commented Feb 6, 2018 at 0:47
  • I don't understand what you are saying. Are you sure this is javascript? Commented Feb 6, 2018 at 0:48
  • @keithlee96 I've added the console log screen. Commented Feb 6, 2018 at 0:49
  • @GaurangDave tried this, and just like above, none of them doesn't work :( Commented Feb 6, 2018 at 0:49
  • @Lukas Can you share the JS code (operation you are performing)? Commented Feb 6, 2018 at 1:10

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

3 Comments

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 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?
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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.