Divide the input field string into distinct arrays based on the delimiter used, either commas or spaces

I am facing an issue with extracting string values from a form input field and grouping them into separate arrays based on whether the words end in a comma or space.

My approach involved splitting the input string using commas as separators, pushing those values to the commaArray, filtering through to extract values separated by spaces, and pushing them to the spacesArray. However, I have not been successful in achieving the desired outcome. Additionally, I need to include the last word in the input field with the spaceSeparatedArray if it does not end in a comma.

To further clarify my problem, I have provided code snippets and created a StackBlitz demo - link is below.

Click here for the StackBlitz demo.

Input String:
"a, b, cd ef gh, ijkl, mnop"

Desired Output Arrays:
commaSeparatedArray = ["a", "b", "gh", "ijkl"]

spaceSeparatedArray = ["cd", "ef", "mnop"]

HTML

<form
[formGroup]="aForm"
(ngSubmit)="onSubmit()">

Value: {{ aForm.value | json }}

  <label>Comma Separator</label>
  
  <input
  formControlName="inputString"
  >
  <button type="submit">Submit</button>
</form>

TypeScript

import { Component } from '@angular/core';
import {FormBuilder, FormControl, FormGroup} from '@angular/forms'
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {

    valuesArray: [];
    
    
  aForm: FormGroup;

  constructor(
    private _formBuilder: FormBuilder
  ){
    this.aForm = this._formBuilder.group({
      inputString: new FormControl()
    })

  }
  // INPUT: 
  // a, b, cd ef gh, ijkl mnop

    onSubmit() {   
      let stringIn = this.aForm.get('inputString').value;
      let commaSeparatedArray = [];
      let spaceSeparatedArray = [];

      stringIn = stringIn.split(',');
      for(let i = 0; i <= stringIn.length; i++) {
        commaSeparatedArray.push(stringIn[i]);
      }
           

      spaceSeparatedArray = commaSeparatedArray.filter(a=> a.includes(' '));

      // OUTPUT 

      console.log("SpaceSeparatedArray:  " +spaceSeparatedArray)

      console.log("CommaSeparatedArray:  " + commaSeparatedArray);
  

    }
}

Thank You

Answer №1

Here is a solution that should do the trick:

const myString = "a, b, cd ef gh, ijkl, mnop"

const separatedByComma = myString.split(' ')
.filter(word => word.slice(-1) === ',').map(word => word.replace(',', ''));

console.log(separatedByComma);

const separatedBySpace = myString.split(' ')
.filter(word => word.slice(-1) !== ',');

console.log(separatedBySpace);

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

How to extract data from a two-dimensional array with 2 columns and 3 rows stored in a single variable using destructuring in JavaScript

I have a variable named data_array that stores an array. The data appears as: 1 car 2 truck 3 boat I want to extract the second column of data based on the first column. If col1 = 1, then var1 = car. If col1 = 2, then var2 = truck. If col1 = 3, then v ...

Traversing arrays and purging elements

Within my CSV table, I have arrays that contain various information such as Name, Email, and Phone Number. The array structure is as follows: Array ( [0] => Array ( [0] => Name [1] => Email [2] => Phone Number ) ...

Guide on Extracting Python/Django Lists and Dictionaries for Use in Javascript

Is there a way to efficiently pass server-side data to JavaScript for display purposes? I have a list of serializable dictionary objects that represent parts of my data model and I want to utilize these in my JavaScript code. Here's how the objects ar ...

Combine two arrays using JQ

I am currently working on parsing JSON output from an API. There are two arrays structured as follows: { "data": [ { "average": null, "count": null, "maximum": 100.0, " ...

Nested views within Angular providing a multitude of perspectives

Currently, I am tackling a project at my workplace with my colleagues, but we are collectively stumped on how to proceed. Consequently, the details may come across as nebulous. Allow me to present a preview of the expected layout: Template The plan is fo ...

Conceal an element depending on the values of surrounding elements

I want to dynamically hide a table based on the values of two fields. If field2 is equal to field1, then I need the table to be hidden. JSfiddle HTML: <form> Expected Number of Items: <input type="text" value="14" name="totalItems" id="tota ...

Smoothly animate the position of a THREE.JS Mesh

Can you help me with a question regarding three.js and x position translation of an imported .obj mesh? I'm new to three.js and looking for guidance on how to solve this issue. Basically, I have a mesh at (0,-200,0) and I want to smoothly move it to ...

Dynamically enhance the JSON root with additional value

Oh dear, I'm feeling quite perplexed right now. I created a JSON element in the following way: var planet = {"continent": []}; planet.continent.push({name: "Asia", flag: "yes", countries: []}); planet.continent[0].countries.push({name: "Japan", capi ...

Incorporating Static JSON data into an AngularJS factory

Can hard coding a bulk of static JSON directly into an AngularJS Factory instead of storing it in separate JSON files cause any issues for my application's performance? 'use strict'; myApp.factory('appUtilityData', function() { ...

Is there a way to narrow down a Backbone collection to only include models that have IDs matching any of the IDs in an array?

I have a list of IDs as shown below: var styles = ["600566", "600568", "600569", "600571", "600572", "600574", "600575", "600577", "600578", "600580"]; In my Styles collection, there are numerous models, and I need to filter this collection to only inclu ...

Guide on creating a service in AngularJS that calls a function from a module utilizing the base module

I am currently developing a versatile service intended for use across various independent websites. However, there are certain instances where the service needs to execute different code based on the specific website it is implemented in. My goal is to mai ...

Angular 13 and Tailwind CSS: A Match Made in Web

After attempting to run : ng add @ngneat/tailwind An unexpected error occurred: NOT SUPPORTED: keyword "id", please use "$id" for schema ID !!!!!! This took place in VSCode. Versions: Angular cli v: 13.1.2 npm v: 8.3.0 ...

Creating a new JSON by extracting a specific branch or node from an existing JSON data

I have a Nuki Smartlock and when I make two API calls to the Nuki Bridge, I receive JSON responses. I want to apply the same logic to both responses: When requesting for current states, the JSON looks like this: [{ "deviceType": 0, "nuk ...

Struggling to invoke the JavaScript function within the HTML code

I have an HTML file named sof.html and a Javascript file called sofjs.js. I am importing the Javascript file inside the HTML and calling its functions in the body's onload() function. Here is the code snippet: However, I noticed that only the HTML co ...

Breaking up arrays within a mongodb dataset

I've been struggling to create a collection of unique strings or arrays without using $unwind due to the presence of other data. To illustrate, consider the following example: Here is a snippet of how my documents are structured: { "key" ...

How can I retrieve specific elements from a JSON response in Angular?

My controller retrieves a json array with only one index, which is a json string containing three properties: whiteLedvalue, blueLedValue, and variousColorLedValue. The code in my controller looks like this: function getLedData() { ledService.getLedDat ...

Show the values of an array if the array name matches the string name

Is there a way to dynamically display the values of an array based on a matching string in Angular 4 or 6? Let's say we have two arrays, A and B: A = ['aaa','arrr','aeee','aqqqq','awwww','axxxx& ...

Ways to eliminate the relationship between parent and child

I am attempting to create a design featuring a large circle surrounded by smaller circles. The parent element is the large circle, and the small circles are its children. My goal is for any circle to change color to red when hovered over, but if I hover ov ...

Say goodbye to document.write?

There is a function defined below: function loadJavaScript(src) { document.write('<' + 'script src="' + src + '"' + ' type="text/javascript"><' + '/script>'); } This ...

Refreshing Information in Angular

I am attempting to create a reload data button. Here is the JSON structure I am working with: [ { "name": "AAAAAA", "data": "False" }, { "name": "BBBBBB", "data": "45%" ...