Home > front end >  Retrieve other item properties too, after executing array.map
Retrieve other item properties too, after executing array.map

Time:10-15

I am mapping a Data array to get My distance to the Points and I get as a result (null filtered, sorted array and then extracted) the Point with the nearest distance to Me. As a result I get "Distance: 234456".

Now I'm trying to do the same thing with a New/same Data array with one more property, and together with the map.distance result, I would get in return the extra property too.

The New Data array would have objects like {id: "1", Point: "-34.910490, -56.201567", A: "4"} so supposing this was going to be the nearest Point, I would get in return "Distance: 234456 and A: 4".

Data : [{id: "1", Point: "27.1597268, 40.6646601"},
        {id: "2", Point: "11.1640393, 49.6487153"},
        {id: "3", Point: "26.1539253, 42.6599287"}, 
        {id: "4", Point: "21.1597268, 44.6646601"}],


const distances = this.state.Data.map(
      (item) =>
        !!(coords.longitude && coords.latitude) &&
        getPreciseDistance(coords, item.Point)
    )
      .filter(Boolean)
      .sort()
      .map((distance) => <Text>{distance},</Text>);

CodePudding user response:

In order to make your function return an object with the properties distance and a you can change your map function to not only return a single value, but to return the object you want:

const distances = this.state.Data.map(
      (item) =>
        !!(coords.longitude && coords.latitude) &&
        // return an object instead of a single number
        ({ distance: getPreciseDistance(coords, item.Point), a: item.a})
    )
      .filter(Boolean)
      .sort()

However, if you are searching for a single item wit the largest distance, I would usually go with a find function in the end of your function chain. This way you can be sure your function only returns one item at all times.

  • Related