0

How to convert array EX-["lat","long","abc","def","abcc","deef",] into [lat,long | abc,def | abcc,deef] in javascript.

I am facing issue with distance matrix Api...

Below is my code

export async function getStoreDistance(locationDetails) {
  destinationRequest = [];
  let destinationRequest = locationDetails.destinations.map(location => {
    console.log('destreqlocation', location);
    return `${location.lat},${location.long} `;
  });

  return await axios
    .get(
      `https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial
      &origins=${locationDetails.origins.map(function(locationDetail) {
        return locationDetail;
      })}
      &destinations=${destinationRequest}&key=**********`,
    )
    .then(function(response) {
      // handle success
      // return response;
    })
    .catch(function(error) {
      // handle error
      return error;
    });
}
Ankit Kumar
  • 118
  • 12
  • 2
    `[lat,long | abc,def | abcc,deef] ` isn't a valid structure ? IMO you need `" or '` around please update accordingly – Code Maniac Sep 29 '19 at 06:18
  • Actually I have a distance array containing lat and long something like destinationrequestsample---> ["0,0", "0,0", "0,0", "0,0", "0,0", "0,0", "0,0", "0,0", "0,0", "0,0", "0,0", "0,0", "0,0", "0,0", "0,0", "0,0", "0,0", "0,0"] and I want to convert this array to pipe separated so that I can use in distance matrix api......I just want the distances and not the map – Ankit Kumar Sep 29 '19 at 07:23

3 Answers3

0

Try something like below

input = ["lat", "long", "abc", "def", "abcc", "deef"];

const [lat, long, ...rest] = input;

res = rest.reduce((acc, val, index) => {
    if(index % 2 === 0) acc.push([]);
    acc[acc.length -1].push(val);
    return acc;
}, []);

resFinal = [[lat, long], ...res];
console.log(resFinal);

resFinalStr = resFinal.reduce((acc, val, index)=> {
    if(index !== resFinal.length -1){
        acc+=(val.join(",")) + "|";
    }else{
        acc += val.join(",")
    }
    return acc;
}, "")

console.log(resFinalStr)
console.log(`[${resFinalStr}]`)
Nithin Thampi
  • 3,579
  • 1
  • 13
  • 13
0

My solution to the problem.

const so1 = ["lat","long","abc","def","abcc","deef"]

let result = so1
  .map((item, id, array) => ((id % 2) !== 0 && id !== (array.length - 1)) ? item + '|' : (id !== (array.length - 1)) ? item + '&' : item)
  .join('')
  .replace(/&/g, ',')

console.log( result )
console.log( `[${result}]` )
Vitaly K
  • 66
  • 6
0

An old-fashioned for loop should do the job fine:

function getStoreDistance(locationDetails) {
  destinationRequest = locationDetails[0] || "";
  for (let i = 1; i < locationDetails.length; i++) {
    destinationRequest += (i % 2 ? "," : " | ") + locationDetails[i];
  }
  return destinationRequest;
}

// Demo
let response = ["lat","long","abc","def","abcc","deef"];
console.log(getStoreDistance(response));
trincot
  • 317,000
  • 35
  • 244
  • 286