Home > front end >  Applying a function to each object in a array
Applying a function to each object in a array

Time:11-30

data=[{id: 4, lat: -33.85664180722481, long: 151.2153396118792},{..},{...}..];

This is my data and I have calculateDistance() function. And location is the location of where mause is clicked on map.What I want is to pass each element in data to pass my calculateDistance() function and save the result in distance array and pass it to useState hook. How can i do that? I get output as NaN array with that code.

 useEffect(() => {
const distance = data.map((hero) => {
  calculateDistance(location?.lat, location?.lng, hero?.lat, hero?.long);
  return calculateDistance();
});
setDistance(distance);},[location, data]);

And here is the calculate distance function

const [distance, setDistance] = useState(null);
  const data = useHeroesData();
  //console.log(data);
  const calculateDistance = (lat1, lon1, lat2, lon2) => {
    // generally used geo measurement function
    var R = 6378.137; // Radius of earth in KM
    var dLat = (lat2 * Math.PI) / 180 - (lat1 * Math.PI) / 180;
    var dLon = (lon2 * Math.PI) / 180 - (lon1 * Math.PI) / 180;
    var a =
      Math.sin(dLat / 2) * Math.sin(dLat / 2)  
      Math.cos((lat1 * Math.PI) / 180) *
        Math.cos((lat2 * Math.PI) / 180) *
        Math.sin(dLon / 2) *
        Math.sin(dLon / 2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    var d = R * c;
    return d; // km
  };

CodePudding user response:

useEffect(() => {
  const distance = data.map((hero) => {
    return calculateDistance(
      location?.lat,
      location?.lng,
      hero?.lat,
      hero?.long
    );
  });
  setDistance(distance);
}, [location, data]);

Or the equivalent:

useEffect(() => {
  const distance = data.map((hero) => calculateDistance(
    location?.lat,
    location?.lng,
    hero?.lat,
    hero?.long
  ););
  setDistance(distance);
}, [location, data]);

CodePudding user response:

According to your code:

 useEffect(() => 
{
  const distance = data.map((hero) => {
    calculateDistance(location?.lat, location?.lng, hero?.lat,hero?.long);
    return distance;
  });
  setDistance(distance);
},[location, data]);

You are returning the distance variable without setting it. This is what is resulting the strage behavior. You should return return calculateDistance instead.

useEffect(() => 
{
  const distance = data.map((hero) => 
  {
    return calculateDistance(location?.lat, location?.lng, hero?.lat, hero?.long);
  });
  setDistance(distance);
},[location, data]);

Or you can return an arrow function to make it cleaner

useEffect(() => 
{
  const distance = data.map((hero) => calculateDistance(location?.lat,location?.lng,hero?.lat, hero?.long));
  setDistance(distance);
}, [location, data]);
  • Related