Locating numerous occurrences of a specific string within an array and rearranging them

I am facing an issue with organizing data stored in the 'names' variable within the code snippet. The task at hand involves converting a string into an array, rearranging the elements within the array to ensure the text is in the correct order. While I have managed to successfully sort the first or last instance of a first & last name individually, I am now looking for guidance on how to handle multiple names efficiently. The current implementation only sorts the last occurrence of the first & last name correctly.

If we consider the input string:

names = "Bond, James & Banner, Bruce";

After processing, the expected output should be:

['James', 'Bond,', '&', 'Bruce', 'Banner,']

Your assistance and insights are highly appreciated. Thank you in advance!

Array.prototype.move = function(from,to){
  this.splice(to,0,this.splice(from,1)[0]);
  return this;
};

var names ="Bond, James & Banner, Bruce";

var namesArr = names.split(' ');
var idx;

// search for a comma (only last names have commas along with them)
for(var i = 0; i < namesArr.length; i++) {
  if(namesArr[i].indexOf(',') != -1) {
    idx = i;
  }
}
namesArr.move(idx, idx+1); 
console.log(namesArr);

Answer №1

You were very close to the solution in this case. All you need to do is update the loop and increment the index i to ensure that the switch is properly accounted for. Failure to do so may result in revisiting the first last name during the switch process.

Array.prototype.move = function(from,to){
  this.splice(to,0,this.splice(from,1)[0]);
  return this;
};

var names ="Bond, James & Banner, Bruce & Guy, Other";

var namesArr = names.split(' ');
var idx;

// Look for a comma (last names are the only ones with commas)
for(var i = 0; i < namesArr.length; i++) {
  if(namesArr[i].indexOf(',') != -1) {
    namesArr.move(i, i+1);
    i++; 
  }
}

console.log(namesArr);

Answer №2

One potential approach is to utilize the String.prototype.match() method along with a regular expression pattern like \w+ to extract and organize names:

var names = "Bond, James & Banner, Bruce & Licoln, Anna"; // ...
var arr_names = names.match(/\w+/g); // Extract individual names
var res = [];

for (var i = 0; i < arr_names.length; i += 2) { // Skip every other name
  res.push(arr_names[i + 1]); // Add the previous name
  res.push(arr_names[i]); // Add the current name
  res.push("&"); // Include "&"
}

res.splice((res.length - 1), 1); // Remove the last "&"
console.log(res);

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

Tips for avoiding multiple function calls in React JS when a value changes

How can I avoid multiple function calls on user actions in my demo application? I have tabs and an input field, and I want a function to be called when the user changes tabs or types something in the input field. Additionally, I need the input field value ...

Tips for managing Material-ui's <Autocomplete/> component based on the option's id

When dealing with HTML select in React, it's common to use an id or key to keep track of the selected value: <select value={value} onChange={(event) => setValue(event.target.value)}> {options.map((option) => ( <option value={optio ...

Handling concurrent requests in DjangoDiscover how Django manages multiple simultaneous requests

Handling multiple requests in a web application can be a challenging task, especially when the server needs to perform complex operations like making API requests and executing database queries. In this post, we will explore how Django can effectively mana ...

Error: Reactjs - Attempting to access the 'name' property of an undefined variable

As I continue to learn about React, I have been experimenting with props in my code. However, I encountered an error where the prop is appearing as undefined. This issue has left me puzzled since I am still at a basic level of understanding React. If anyo ...

Form a collection of X amount of words using a string in JavaScript

Hello amazing Stack community, I am currently striving to create a straightforward JavaScript function that can accurately count the total number of words from a given string value. Furthermore, I aim to store a specific number, X, of words into an array ...

Determine the number of days without including weekends and holidays using JavaScript

I am working on a code that calculates the total number of days excluding weekends and specified holidays. After researching on various platforms like stackoverflow and adobe forum, I have come up with the following code. If a public holiday falls on a w ...

Angular Selectable Drop-down Menu

I'm facing an issue with using angularjs for dropdown with multiple selection. When I try to include 2 dropdowns in the same form, only one of them gets initialized properly. Here is a sample code snippet http://jsfiddle.net/vUSPu/1221/. Can someone p ...

Is my jQuery code generating a large number of DOM objects?

I am currently developing a hex dumper in JavaScript to analyze the byte data of files provided by users. To properly display a preview of the file's data, I am utilizing methods to escape HTML characters as outlined in the highest-rated answer on thi ...

The system does not acknowledge NPM as a valid internal or external command

Here is the content of my package.json file for the server directory, which I am attempting to launch: { "name": "server", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start": "nodemon src/app.js --exec 'npm ...

The interval becomes congested due to the execution of two simultaneous Ajax calls

I have an Interval set to run a function every 3 seconds. intervalStepper = window.setInterval('intervalTick()','3000'); function intervalTick() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari ...

Steps to altering the color of a second button with a button click

My goal is to create a button click function that allows only one button to be clicked at a time. For instance, when btn1 is clicked, its background color changes from transparent to green. Then, if btn2 is clicked, btn1's background color should chan ...

Angular 5 is throwing an error that says: "There is a TypeError and it cannot read the property 'nativeElement' because it

Being aware that I may not be the first to inquire about this issue, I find myself working on an Angular 5 application where I need to programmatically open an accordion. Everything seems to function as expected in stackblitz, but unfortunately, I am enco ...

Consider creating a distinct document for your "scripts"

Within my package.json configuration file, the "scripts" section contains numerous commands structured as shown below. "scripts" { "script1": "command example", "script2": "command example", "script3": "command example", "script4": "command exampl ...

Is it possible that when using Sequelize fixtures to import a model as a function, errors occur if the data is not properly imported from a JSON

I'm currently working on a node.js project that utilizes express and sequelize. I want to add fixtures to populate my data tables. For this purpose, I am using the Sequelize-fixtures npm package. Below is the content of my fixtures.js file: 'us ...

Tips for ensuring nvm is activated whenever the nvmrc file is updated

I have implemented the use of direnv along with an nvmrc file to ensure that nvm install runs every time the directory is entered. This ensures that the correct node version is used when working on the project. However, I have noticed that if another user ...

Dynamic, AJAX-driven content is experiencing a 200 status code

Is it necessary for a single-page website, which dynamically loads content via ajax and utilizes browser session history stacking, to return a "200 Status" for each successful state change? The core code of my website is as follows: $(document).on('c ...

What is the method for creating an array of strings in VueJS?

In my VueJS and Vuetify project, I am working on creating a modal that allows users to input strings into a text field. What I aim to achieve is adding the inputted string to an array when the user clicks on create button. For example, if I enter 'inp ...

Troubleshooting a problem with data retrieval in Hygraph and Next JS

I'm currently facing an issue while attempting to fetch data from Hygraph in a fresh Next JS application. The error message I'm encountering is: Error: Cannot read properties of undefined (reading 'map'). As a beginner in both technolo ...

Converting an array or JSON to a string

Converting a string to an array: $string = '[{"name":"jack","address":"who knows"},{"name":"jill","address":"who knows too"}]'; $array = json_decode($array,true); But what if we want to reverse it and convert an array back to a string: $array ...

I am encountering issues in Vue JS when using ternary expressions alongside v-if statements

Snippet:- <template> <div id="calendars-results"> <div class="vs-con-loading__container"> <div class="vs-row flex justify-between"> <h4 class="vs-row mb-2">{{ title } ...