将数组转换为管道分隔

Convert array to pipe separated

如何转换数组EX-["lat","long","abc","def","abcc","deef",] 进入 [lat,long | abc,def | javascript.

中的 abcc,deef]

我遇到距离矩阵问题Api...

下面是我的代码

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;
    });
}

试试下面的方法

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}]`)

我的问题解决方案。

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}]` )

老式的 for 循环应该可以很好地完成工作:

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));