Group the elements of the second array based on the repeated values of the first array and combine them into a single string

I have a challenge with two arrays and a string shown below

var str=offer?;

var names = [channelId, channelId, offerType, offerType, Language];

var values =[647, 763, international, programming, English];

Both arrays are the same size.

I want to create a formatted string like this

final string = offer?channelId=647,763&offerType=international,programming&language=English

This task needs to be achieved using JavaScript.

I attempted it this way:

   var namesMatched=false;
   for(var i=0; i<names.lengthl; i++){
      for(var j=i+1; j<names.length; j++){
       if(names[i]==names[j]){
         str=str+names[i]+"="+values[i]+","+values[j];
         namesMatched=true;
         continue;
       }
       else if(namesMatched){
          str=str+"&";
          i=names.length-j;
       }
       else{
         str=str+names[i]+"="+values[i]+"&";
         break;
       }
      }
    }

However, it is not producing the expected outcome.

Your assistance here would be greatly appreciated.

Answer №1

Below is a more concise solution that avoids using two separate for loops:

let sentence='offer?';
        
        let labels = ['channelId', 'channelId', 'offerType', 'offerType', 'Language'];

    let dataValues =[647, 763, 'international', 'programming', 'English'];

let previousLabel = '';

for (let i=0; i<labels.length; i++) {
  let currentLabel = labels[i];
  if (previousLabel === currentLabel) {
    sentence+=','+dataValues[i];
  } else {
      if (i !== 0) {
        sentence+='&';
      }
    sentence+=currentLabel+'='+dataValues[i];
  }
  previousLabel = currentLabel;

}

console.log(sentence);

http://jsbin.com/kinefipalu/edit?html,js,output

Answer №2

You have the option to utilize explanatory comments within your code.

var str='offer?';
var names = ['channelId', 'channelId', 'offerType', 'offerType', 'Language'];
var values = [647, 763, 'international', 'programming', 'English'];

var temp = names.reduce(function (a, b, i) {
    // Create an array object for each name if it does not already exist
    a[names[i]] = (a[names[i]] || [])
    // Add the value to the array
    a[names[i]].push(values[i])
    return a;
}, {})

// Iterate through the properties of the temporary object (a collection of value arrays tagged by name)
var output = str + Object.keys(temp).map(function (e) {
    // Build the substring for each key
    return e + '=' + temp[e].join(',');
// Join the substrings using &
}).join('&')

console.log(output)

Steps

  1. The initial step involves utilizing reduce to consolidate the two arrays into a single object (temp). Each unique name becomes a property on the object with corresponding array values.

  2. Next, apply Object.keys() to retrieve all keys (names) from the temporary object.

  3. Using map, convert the names and their associated value arrays into substrings.

  4. Lastly, employ join to merge these substrings together.


var str='offer?';
var names = ['channelId', 'channelId', 'offerType', 'offerType', 'Language'];
var values = [647, 763, 'international', 'programming', 'English'];

var temp = names.reduce(function (a, b, i) {
  // Create an array object for each name if it doesn't already exist
  a[names[i]] = (a[names[i]] || [])
  // Push the value onto the array
  a[names[i]].push(values[i])
  return a;
}, {})

// Loop through the properties of the temporary object (a collection of value arrays tagged by name)
var output = str + Object.keys(temp).map(function (e) {
  // Construct the substring for each key
  return e + '=' + temp[e].join(',');
  // Join the substrings using &
}).join('&')

alert(output)

Answer №3

If you're comfortable utilizing Underscore, there's a way to group the values simply by using

groups = _.groupBy(values, function(val, i) { return names[i]; });

In essence, this method organizes the values according to the corresponding name from the names array. This results in

{ channelId: [647, 763], ... }

You can convert this into your desired string format with ease using

_.map(groups, function(val, key) { return key + '=' + val; }) . join('&');

It's worth noting that in the line above, the val, being an array, will automatically combine its elements with a comma when coerced into a string.

Alternatively, depending on your coding style preference:

function name(val, i)  { return names[i]; }
function key(val, key) { return key + '=' + val; }

_.map(_.groupBy(values, name), key) . join('&')

or through chaining:

_.chain(values) . groupBy(name) . map(key) . join('&') . value()

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

Strange Node.js Issue

I don't have much experience with node.js, but I had to use it for launching on Heroku. Everything was going smoothly until a few days ago when suddenly these errors started appearing. Error: /app/index.jade:9 7| meta(name='viewport', co ...

Obtaining the value of a checkbox with React

I have a form with two input fields (email, password) and a checkbox. The code for the form is shown below: <Box component="form" onSubmit={handleSubmit} noValidate sx={{ mt: 1 }}> <TextField margin="normal" required ...

How can I define an HTML array in PHP when it shows an "Undefined Index" error?

Hey there, I have a quick question about PHP that I've been learning. In the code snippet below, why is $html[$firstname] showing up as an undefined index in the server error logs? Any quick help would be greatly appreciated. Here's the full cod ...

What is the reason for the vertex shader failing to compile?

Recently diving into the world of WebGl, I decided to experiment with a simple example. Here is how I set up my script: Here's my setup script import testVertexShader from './shaders/test/vertex.glsl' import testFragmentShader from './ ...

Pause animation when hovering over their current positions

I am working on a project with two separate divs, each containing a circle and a smiley face. The innercircle1 div is currently rotating with a predefined animation. My goal is to create an effect where hovering over the innercircle1 div will pause its rot ...

"An easy way to dynamically update a select dropdown based on the data of the corresponding row in a table using jQuery

Having some trouble with dynamically populating form input fields in a table. The first row works fine, but when I change the select option in the second row, it affects the previous field instead of the current row: How can I ensure that changing the sel ...

How can I iterate through each element of MySelector in the callback function of jquery-ui's draggable function?

When using: jQuery(MySelector).dragabble( start: function( e, ui ) { } ) In the start function: The start event provides $(this) with the current dragged element from MySelector. How can I loop through each element in MySelector to apply additional code ...

Tips for enhancing the clarity of elements in KineticJS

I'm new to using Kinetic JS, and while I think it's a great library, I'm having trouble with the resolution of the elements. I know that Kinetic JS doesn't use SVG, but the resolution is not up to par. I'm creating circles and othe ...

Why is my Javascript XMLHttpRequest onreadystatechanged event not triggering?

I am facing an issue with my html file and a .txt file stored in the same directory on a webserver. In the html file, I have the following code: <html> <head> <script> window.onload = function() { receiveMessage(); } function recei ...

Retrieving server information using AJAX in React

I've been attempting to utilize an AJAX call in order to fetch server data for my React Components. However, I'm encountering difficulties when it comes to displaying it with React as I keep receiving this error: Uncaught TypeError: Cannot read ...

Add the bannercode snippet found on a webpage

I am currently facing an issue with appending a banner code to the end of a URL. The scenario is as follows: An individual receives an email with a link to a website (SITE1), where the URL includes a banner code, such as www.site1.com?banner=helloworld O ...

The rendering of HTML DOM is being obstructed on iPhone devices running iOS 13

Currently, I'm developing a web-based URL stream music player using JavaScript. The player functions smoothly on Android devices, but I'm encountering an issue with DOM rendering being blocked on iPhone devices. Despite rearranging the JavaScript ...

What is the best way to display an alert when the button is clicked repeatedly?

Is it possible to keep displaying the alert every time we click the button, rather than just once after clicking it? I currently have an alert set to trigger when a button is clicked, but it disappears after 3 seconds. How can I make it show up again with ...

JavaScript click or text-to-speech

Currently, I am working on a web application that is designed to automatically read text. Below is the code snippet that I am using: function hablalo() { var palabra = new SpeechSynthesisUtterance('Casilla 6 turno E18'); palab ...

Clicked button redirects user to the parent URL

When the application is running on page http://localhost:3000/login, clicking a button should redirect to http://localhost:3000/. This is how I attempted it: import React from 'react'; import { Redirect } from 'react-router-dom'; impor ...

Obtain the dynamic identifier of an element within every block using jQuery in a rails application

Let me illustrate my issue with a simple example. I am currently developing a recipe application. Within the show partial that loads via AJAX, I have the following setup: _show.html.erb <% @recipe.ingredients.each do |ingredient| %> <div class ...

Show 1 Blog Post on a Separate AngularJS Page

I would like to show only Test Post 1 on the next HTML page titleDetails.html when the user clicks on Test Post 1 in index.html 1) titleDetails() in index.html: <a ng-click="titleDetails(post)">{{ post.title }} </a> 2) Controller Variables a ...

The periodLookup array does not have a defined value for periodStr. Why is this error being caught?

Here is a method that I am working with: set_period_help_text: function(periodInput){ var metric = MonitorMetric.getSelectedMetric(); var periodStr = $('select[name=metric_period]').val(); var datapoints = Number(periodIn ...

Dropdown selection for countries that dynamically updates region choices

Looking to implement some JavaScript, preferably using jQuery, to create a cascading dropdown menu. Initially displaying a list of countries and upon selection, the corresponding regions for that country will be displayed in another dropdown. I assume an ...

Is there a way to resolve the MongoDB Database-Differ Error?

I am currently working on creating an API and have set up a brand new Project, cluster, and Collection for it. However, when I attempt to use mongoose.save() to add data to my database, I keep receiving an error message. "message": { " ...