Combine a specific number of elements in an array using JavaScript's comma-separated join without relying on jQuery

In my current project utilizing Vue and Quasar, I am hesitant to incorporate jQuery. Any suggestions on how to achieve a comma-separated string from an Array without using a loop? Ideally, I want to only combine a specific number of elements together.

  Array.join(',') 

Let's say, for instance, I have a list of publication IDs, where I need to eliminate duplicates and then group them into sets of 200 due to limitations with the web service. The initial array could potentially contain thousands of items.

30310060,30166592,29704517,29662190,29533787,28114741,27456065,27208808,26208975

The process involves sending chunks of 200 IDs at a time until the entire list has been processed. Eventually, the final string must be converted to JSON before transmitting it to the server. Any advice on handling this scenario would be greatly appreciated.

Answer №1

Does this code snippet seem suitable for your needs?

extractFirstN = function(array, number, separator){
   firstNElements = array.slice(0, number);
   return(firstNElements.join(separator));
}

This function extracts the first specified number of elements from an array and then concatenates them into a string. You can use it like this:

extractFirstN(array, 200, ",");

Answer №2

To eliminate the use of external libraries and stick to ES6, you can leverage an object to remove duplicate values in an array. You can then employ an asynchronous function to sequentially process a specified number of elements at a time, send them to the server, and upon receiving a response, proceed with the next batch. This approach can also be adapted to concurrently submit multiple batches if your server supports it, as opposed to submitting each batch one after the other.

// Create an object using the ids to ensure uniqueness
// Extract only the unique keys (or values)
const uniqueIds = Object.keys(ids.reduce((ids, id) => {
  ids[id] = id
  return ids
}, {}))

const submitInBatches = async (ids, batchSize) => {
  // Exit condition: no more ids remaining
  if (ids.length === 0) return

  // Take the next batch of ids and submit them
  const batch = ids.slice(0, batchSize)
  const results = await fetch(`/your/service?${batch.join(',')}`)
  // Process the results

  // Recursively call with the remaining ids
  return submitInBatches(ids.slice(batchSize), batchSize)
}

submitInBatches(uniqueIds, 200)

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

Encountering an error: "SyntaxError: Identifier 'createApp' has already been declared" while trying to open Vue 3 within a Bootstrap modal

Upon loading page2 with Vue in a bootstrap modal within page1, an error is thrown: SyntaxError: Identifier 'createApp' has already been declared Content of page1.html: <script> const { createApp, ref } = Vue cr ...

What is causing this issue with my jQuery UI animation?

Below is the HTML code snippet: <div id="menu_status_item"> <span class="menu_status_bar"></span> </div> Here is the CSS code: #menu_status_item { margin-top: 40px; width: 100%; } .menu_status_bar { margin-le ...

New post: "Exploring the latest features in Angular

Looking for help with integrating Angular and SpringREST to fetch data from the backend? Here's my situation: I need to retrieve a JSON string from the backend using a POST request, send it to my site's hosted link, and display it on the user int ...

Analyzing and sorting two sets of data in JavaScript

I am currently working with two arrays that are used to configure buttons. The first array dictates the number of buttons and their order: buttonGroups: [ 0, 2 ] The second array consists of objects that provide information about each button: buttons = ...

Guide on deploying Nuxt JS to Netlify in production mode

I've built my app using Nuxt.js and now I'm looking to deploy it on Netlify. First step is to configure my deployment settings: Repository on git Base directory: Not specified Build command: npm run build && npm run start Publish dir ...

Using JavaScript, capture and rearrange the colors of the store's section. JS

I'm facing a challenge with creating dynamically colored divs based on different sections in the background. While I can achieve this using CSS, I wonder if there's a more efficient way to handle the colors with JavaScript. In my current setup, ...

What steps can be taken to further personalize this pre-existing jQuery sorting solution?

After coming across a solution for adding sorting capabilities to jQuery (source: jQuery sort()), I decided to tweak it to handle strings of variable lengths. Although the modified function sorts in ascending order, I found it quite effective. jQuery.fn.s ...

Unable to import the configuration module that is located three directories away in a Node.js environment

Within user.controller.js, there is a line that reads as follows: const config = require(".../config");. To provide some context, here is a visual representation of my directory structure: https://i.stack.imgur.com/dCkp1.png ...

Tap on the child to reveal their parent

I am working with a family tree that includes dropdown menus containing the names of parents and children. Each child has a link, and when I click on a child's link, I want their father to be displayed in the dropdown menu as the selected option. Can ...

Mapping URLs to objects in JavaScript, TypeScript, and Angular4

I have implemented a class called SearchFilter class SearchFilter { constructor(bucket: string, pin: number, qty: number, category: string) { } } When the user performs a search, I populate the filter i ...

Tips for customizing font color on Google Maps Marker Clusterer

Is there a way to adjust the font color of a markerclusterer marker? Below is my current code for customizing the marker's style: mcOptions = {styles: [{ height: 27, url: "image.png", width: 35 ...

One way to organize data from my API is by sorting it based on two date conditions. If one of those conditions is missing, the data should be placed at the beginning of the list

I am facing a challenge with sorting the return from my API based on the StartDate. However, I need to implement a validation where if there is no FinalDate provided, the data should appear at the first index of the result. StartDate: "2004-06-04" ...

What steps should I take to address the error message "TypeError: express-validator is not a function

I am currently utilizing express-validator version 6.4.0 and encountering an error when running the server. I have attempted to implement custom validation by organizing separate files for validator, controller, and routes. Here is the primary server file ...

Removing all text inside an input field with Vue

I am trying to create a password input field using type 'text' instead of 'password.' <input type="text" v-model="form.password" @input="test" /> <input type="hidden" v-model="form.hiddenPassword" /> As part of my approach ...

What causes the variance in outcomes between employing a literal string versus a local variable?

Here is a loop that I am working with: for (var key in criteria) { var exists = Object.keys(item).some(function(k) { return item[k] === "Test"; }) } Initially, this loop functions as expected and returns 15 trues based on the number of i ...

Preventing the Vue compiler from managing static assets: A step-by-step guide

In my Vue 3 application, I have a variety of static assets that are organized in their own file structure separate from the app's source directory. Fortunately, my web server is configured to serve files from both the Vue build directory and the stati ...

Presented is the Shield UI JavaScript sparklines chart

I'm experimenting with the new lightweight ShieldUI Sparklines chart. I've copied the code directly from this page: Now, when I try to run it on my computer, I'm encountering an unexpected issue. I can see text, but the chart itself is not ...

Encountering issues with ng-repeat in the third iteration

Having Trouble with ng-repeat on the Third Loop (Third Level) <div ng-repeat="child in jdata.children"> <div ng-repeat="childsub in child.children"> <div ng-repeat="text in childsub.text"> {{ text.va ...

Transform the JSON response into a map

I have a functioning code that I am looking to adjust. let table_specs = {'columns': [ {'name': 'Col1', 'width': 7, ....}, {'name': 'Col2', 'width': 8, . ...

Issue encountered when updating npm to version 5.4.2: Unable to locate modules in ./node_modules/react-router-dom

When attempting to update my npm version from 3.10.10 to 5.4.2 and migrate react from 15.3.0 to 16.0, I deleted the node_modules folder and re-ran npm install. However, upon trying to run my application again, I encountered the following error: ERROR in ./ ...