Transform the array into a series of values separated by pipes

How can I transform an array like this - ["lat","long","abc","def","abcc","deef",] into [lat,long | abc,def | abcc,deef] using javascript?

I am currently encountering an issue with the distance matrix API...

Here is the code snippet I have:

export async function getStoreDistance(locationDetails) {
  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;
    });
}

Answer №1

Here is how I approached the issue at hand.

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

let modifiedArray = array
  .map((element, index, array) => ((index % 2) !== 0 && index !== (array.length - 1)) ? element + '|' : (index !== (array.length - 1)) ? element + '&' : element)
  .join('')
  .replace(/&/g, ',')

console.log( modifiedArray )
console.log( `[${modifiedArray}]` )

Answer №2

Give this code a shot

data = ["apple", "banana", "cherry", "date", "elderberry", "fig"];

const [firstFruit, secondFruit, ...restFruits] = data;

res = restFruits.reduce((accumulator, value, index) => {
    if(index % 2 === 0) accumulator.push([]);
    accumulator[accumulator.length - 1].push(value);
    return accumulator;
}, []);

finalResult = [[firstFruit, secondFruit], ...res];
console.log(finalResult);

finalResultString = finalResult.reduce((accumulator, value, index) => {
    if(index !== finalResult.length -1){
        accumulator += (value.join(",")) + "|";
    } else {
        accumulator += value.join(",");
    }
    return accumulator;
}, "");

console.log(finalResultString)
console.log(`[${finalResultString}]`)

Answer №3

To efficiently handle this task, consider using a traditional for loop:

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

// Example
let locations = ["A","B","C","D","E","F"];
console.log(calculateTotalDistance(locations));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Art of Validating Forms in Vue.js

Currently I am in the process of developing a form with validation using Vue, however, I've run into some errors that are showing up as not defined even though they are currently defined. HTML <form class="add-comment custom-form" @submit="checkF ...

How can JavaScript be used to rearrange the placement of DOM elements?

<!DOCTYPE html> <html> <head> <title></title> </head> <body> <div class="boxes"> <div class="red" style="width: 300px; height: 300px; color: red"></div> <div class="blue ...

AngularJS has encountered an error due to exceeding the maximum call stack size limit

Utilizing AngularJS and a web API, I am fetching data from an SQL table. I have designed a function that populates input fields with values when a row is selected from an HTML table. However, I encountered an error during debugging when clicking on any row ...

Having trouble with the append() function in Swift arrays

Looking for assistance with the append method in Swift as I am new to the language and struggling to make it work. Below are my models and view: import SwiftUI struct ContentView: View { @Binding var gameInformation: GameInformation var body ...

Issue encountered while generating dynamic Routes using the map function

When attempting to dynamically use Route from an array, I encounter an error. Warning: Incorrect casing is being used. Use PascalCase for React components, or lowercase for HTML elements. The elements I am utilizing are as follows: const steps = [ { ...

Click the ng-focus button to focus the textarea

I am in need of a solution where I can trigger a button within the ng-repeat loop and focus on a textarea specific to that item in the loop. HTML <div ng-repeat="item in items"> <textarea focus-when="showTextarea">{{ item }}</textarea> ...

a guide on retrieving FormData objects in PHP

Hey everyone, I have a question regarding a sample code snippet I posted here. In this code, I am successfully uploading a file using Ajax JQuery. However, I am struggling to figure out how to read the content of the uploaded file in my PHP code. Can anyon ...

Issues with the History API in AJAX Requests

Recently, I have come across a dynamically generated PHP code: <script> parent.document.title = 'Members | UrbanRanks'; $("#cwrocket_button").click(function(){ $("#module").load("modu ...

The hierarchical structure in the DOM that mirrors an HTML table

While working on code to navigate the DOM for a table, I encountered an unexpected surprise. The DOM (specifically in FF) did not align with my initial expectations. Upon investigation, it appears that FF has automatically inserted a tbody along with sever ...

Updating arrays with empty fields in mongodb

I need help updating an array in my database which currently doesn't have any fields. Can anyone suggest a way to add fields to the existing empty array? Schema const UserSchema = new Schema({ User: [{ Name:{ type: ...

Creating crypto.createCipheriv arguments from fixed origins

Currently, I am implementing a code snippet in my node.js application to perform string encryption. I am seeking guidance on how to create the KEY and HMAC_KEY from a predetermined source. At the moment, these keys are randomly generated within the progra ...

Best practices for using Promises in NodeJS

I'm in the process of developing a library that builds on top of amqp.node (amqplib), focusing on simplifying RabbitMQ functionality for our specific project needs. This new library is designed to utilize Promises. So, for instance, when subscribing ...

tips for iterating through a json string

When retrieving data from PHP, I structure the return like this: $return['fillable'] = [ 'field_one', 'field_two', 'field_three', 'field_four', 'field_five', ]; $json = json_ ...

A guide on extracting information from arrays using JavaScript

Can you show me how to retrieve the name, age, and salary from the products array? Also, could you please explain what is wrong with the code? var products = [ {name: 'John', age: 30, salary: 400}, {name: 'Jane', age: 31, salary: 500 ...

Validating user input fields to display error messages when empty

As part of my program, I need to gather information from users regarding their name and the number of pets they have. If a user enters an empty string, I want to display an error message prompting them to input something and fill the text box with their en ...

What is the process for creating a modal transition?

I am attempting to add animation to a modal using a transition effect. My goal is to open it slowly, either from the center of the screen or from the bottom. However, I am struggling to understand how this can be achieved... While searching on Google, I c ...

What is the best method for saving inert data in Vuex?

Once the VueJS application is initialized, I have certain data loaded on the page that will remain static until the HTML page is reloaded. This data is in the form of a nonReactiveObjectWithSomeNestedData example: const nonReactiveObjectWithSomeNestedData ...

techniques for utilizing dynamic variables with the limitTo filter in AngularJS

<div class="container"> <div class="row" ng-repeat="cmts in courCmt.argument" ng-init="getUserInfo(cmts)"> <div class="col-sm-1 col-xs-2"> <div class="thumbnail"> &l ...

Concealing empty rows within a vertical v-data-table using Vue

Below is the code that can be run to showcase my issue. Design: <div id="app"> <v-app id="inspire"> <v-data-table :headers="headers" :items="desserts" hide-default-header ...

The response from Ajax is not in object form

The output I received from my AJAX request is: ["1","O"] Though I need to extract the number 1 from it, when I use the code: console.log(result[0]); It returns: '[' Any suggestions on how to convert it to an object and retrieve only the f ...