-1

I have an array that adds values dynamically but sometimes returns undefined as a value, I want to know how can I remove all the undefined values.

This is my code:

var arr =[//Values]

let forDeletion = [undefined]
arr = arr.filter(item => !forDeletion.includes(item))

But obviusly this is not working

Victor Escalona
  • 545
  • 1
  • 6
  • 15

2 Answers2

1

Try

let forDeletion = [1,undefined, null, 'a']

let arr = forDeletion.filter(x=> x!==undefined )

console.log(arr);
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
  • @TylerRoper OP use `includes` function – Kamil Kiełczewski Aug 21 '19 at 16:37
  • 1
    Well yes, but what does your code do differently? What was OP's question that you're answering? – Tyler Roper Aug 21 '19 at 16:37
  • I understand that OP ask about the way of filter out `undefined` values – Kamil Kiełczewski Aug 21 '19 at 16:38
  • The problem is that OP's code works fine, so even if this *does* work for OP, it provides nothing to future readers. It doesn't explain what was wrong (*which, again, there is nothing wrong*), doesn't explain why this is a solution, etc. I agree that it's a better *alternative* to OP's code, but I just don't see how it's an "answer". Perhaps it should be a comment. – Tyler Roper Aug 21 '19 at 16:40
  • @TylerRoper - I test OP code and it works wrong - delete all items – Kamil Kiełczewski Aug 21 '19 at 16:54
  • Using the example array from your answer, [OP's code produces the same exact output](https://jsfiddle.net/nz4fhvpL/). – Tyler Roper Aug 21 '19 at 16:55
  • @TylerRoper yes you are right - I don see that he use filter on `arr` not forDeletion - however (he's code looks wired) - however he write that his code not works - so may be he make mistake writing code in question? – Kamil Kiełczewski Aug 21 '19 at 17:00
1

const arra1=["aa",1,2,undefined,true,null]
console.log(arra1.filter(element=>element !==undefined))
Mohammed Al-Reai
  • 2,344
  • 14
  • 18