user20183430
user20183430

Reputation: 15

How to cut a string that is a value of an array in 2?

I have this array that has length = 3:

 state = ["q0", "q1", "q2,q3"]

And I want to modify that, and I want it to look something like this:

 state = ["q0", "q1", "q2", "q3"] // length = 4.

I want to cut the string = "q2,q3" in a way that I will get "q2" and "q3" so that I can replace the state[2] value with "q2" and automatically add to the array like state[3] = "q3".

Does anyone know how can I do it?

I tried the split method but it didn't work as I wanted.

Upvotes: 0

Views: 72

Answers (7)

PeterKA
PeterKA

Reputation: 24638

Per @TrevorDixon's solution, Array#flatMap is the way to go. In case you have multiple separators you can use a regular expression with String#split as in the following demo:

const
    input = ["q0", "q1", "q2,q3","q4 q5| q6"],
    
    output = input.flatMap(v => v.split(/[ ,|]+/));
    
console.log( output );

Upvotes: 0

David Thomas
David Thomas

Reputation: 253308

One simple, and frankly naive, means of achieving this:

// initial state, chained immediately to
// Array.prototype.map() to create a new Array
// based on the initial state (["q0", "q1", "q2, q3"]):
let state = ["q0", "q1", "q2, q3"].map(
  // str is a reference to the current String of the Array
  // (the variable name is free to be changed to anything
  // of your preference):
  (str) => {
    // here we create a new Array using String.prototype.split(','),
    // which splits the string on each ',' character:
    let subunits = str.split(',');
    
    // if subunits exists, and has a length greater than 1,
    // we return a new Array which is formed by calling
    // Array.prototype.map() - again - and iterating over
    // each Array-element to remove leading/trailing white-
    // space with String.prototype.trim(); otherwise
    // if the str is either not an Array, or the length is
    // not greater than 1, we return str:
    return subunits && subunits.length > 1 ? subunits.map((el) => el.trim()) : str;
  // we then call Array.prototype.map():
  }).flat();

// and log the output:
console.log(state);

References:

Upvotes: 0

Benjie Alaan
Benjie Alaan

Reputation: 16

You can do it using three javascript methods. forEach(), concat(), and split(). One liner

let result = []

state.forEach(a => result = result.concat(a.split(",")))

Upvotes: 0

Trevor Dixon
Trevor Dixon

Reputation: 24342

flatMap is perfect for this.

["q0", "q1", "q2,q3"].flatMap(v => v.split(','))

flatMap maps and then flattens. So mapping using split gives you [['q0'], ['q1'], ['q2', 'q3']], then flattening unwraps each second-level array.

Upvotes: 2

Can Ozdemir
Can Ozdemir

Reputation: 36

Hello I gave an example with gets the gap in the last index and splits it

let deneme = ["first","second","third fourth"];


let index = deneme[2].indexOf(" ");  // Gets the first index where a space occours
let firstPart = deneme[2].slice(0, index); // Gets the first part
let secondPart = deneme[2].slice(index + 1);

console.log("first try" ,deneme);
deneme[2] = firstPart;
deneme.push(secondPart);
console.log("second look",deneme);

Upvotes: 0

Vivekanand Vishvkarma
Vivekanand Vishvkarma

Reputation: 115

let state = ["q0", "q1", "q2,q3"];
state=state.join(',');
state=state.split(',');
console.log(state);

Upvotes: 0

Lukáš Gibo Vaic
Lukáš Gibo Vaic

Reputation: 4420

I would iterate over state, try to split each value and then push them to res array.

const state = ["q0", "q1", "q2,q3"];

const res = [];

state.forEach((value) => {
  const splitValue = value.split(",");
  res.push(...splitValue);
});

Upvotes: 0

Related Questions