2

I wanted to ask how to filter my array. In this case my array fills with null object and no null object

[null,{"position":{"lat":50.8999208,"lng":20.6258},"vin":22222}]

normally if null doesn't appear the array looks like this:

`[{"position":{"lat":22.8999208,"lng":22.6258},"vin":11111},{"position":{"lat":50.8999208,"lng":20.6258},"vin":22222}]`

But in this case in my programming scenario the first object is nulled and I have to filter this array or maybe copy no-null objects from this array to another array and then compute or error will occur. How should I do it?

Best regards!

5
  • How are you getting this array? From an API? Commented Dec 14, 2019 at 21:32
  • array.filter(Boolean) Commented Dec 14, 2019 at 21:33
  • Yes, from my API Commented Dec 14, 2019 at 21:33
  • While it may be an issue with the way you are getting the data, Nina's answer should suffice. Commented Dec 14, 2019 at 21:34
  • Does this answer your question? Filter null from an array in javascript Commented Dec 14, 2019 at 21:36

2 Answers 2

5

You could filter the array by checking the data.

var array = [null, { position: { lat: 50.8999208, lng: 20.6258 }, vin: 22222 }],
    withoutNull = array.filter(v => v !== null);

console.log(withoutNull);

Sign up to request clarification or add additional context in comments.

Comments

3

Or just check truthy values:

truthyValues = array.filter(v => v);

let array = [null,{"position":{"lat":50.8999208,"lng":20.6258},"vin":22222}],
    truthyValues = array.filter(v => v);

console.log(truthyValues);

Comments

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.