Search code examples
angularjslodashangular-google-maps

Problem Using _.compact lodash to eliminate null values on an array of objects


I'm manipulating an array of objects that i get from an http request containing coordinates to create markers in google-maps , but i need to eliminate all the null values in the array. I'm trying with compact but it gives back the same array unchanged.

//this is the resulting array structure

var array=
[{"id":0,"latitude":45.17850875854492,"longitude":7.773523330688477},{"id":1,"latitude":45.122344970703125,"longitude":7.7135162353515625},{"id":2,"latitude":null,"longitude":null},{"id":3,"latitude":45.11630630493164,"longitude":7.730717658996582},{"id":4,"latitude":45.116214752197266,"longitude":7.730687141418457},{"id":5,"latitude":null,"longitude":null}]

var comp =_.compact(array) 

i dont get any error in the cosole , but the variable comp return the same exact array without removing null values


Solution

  • All your values are arrays, and the null is a value of your properties. The _.compact() method works with primitives.

    Use _.reject() and check with _.isNull if the properties are null, and the object should be removed:

    const array =
    [{"id":0,"latitude":45.17850875854492,"longitude":7.773523330688477},{"id":1,"latitude":45.122344970703125,"longitude":7.7135162353515625},{"id":2,"latitude":null,"longitude":null},{"id":3,"latitude":45.11630630493164,"longitude":7.730717658996582},{"id":4,"latitude":45.116214752197266,"longitude":7.730687141418457},{"id":5,"latitude":null,"longitude":null}]
    
    const result = _.reject(array, ({ latitude, longitude }) =>
      _.isNull(latitude) || _.isNull(longitude)
    )
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>