0

I have an array that looks like this:

["text1[483]", "text 2[411]", "text 3[560]", "text[484]"]

What I need to do is to create from the values of this array about I need to create 2 new arrays.

One array will contain the text and the [] and anything inside should disappear from it.

The other array would just contain the numbers without the []

So, the new arrays would look like this:

TextArray:

["text1", "text 2", "text 3", "text"]

NumberArray:

["483", "411", "560", "484"]

How can I do this?

3 Answers 3

1

var initialArray = ["text1[483]", "text 2[411]", "text 3[560]", "text[484]"];
    
var texts = initialArray.map(function(v){  return v.split('[')[0]} );

console.log(texts);
// ["text1", "text 2", "text 3", "text"]
    
var numbers = initialArray.map(function(v){  return +v.match(/\[(\d+)\]/)[1]} );

console.log(numbers);
// [483, 411, 560, 484]

Sign up to request clarification or add additional context in comments.

Comments

0

You can split based on [ and remove the last char of the string ]

var arr = ["text1[483]", "text 2[411]", "text 3[560]", "text[484]"];

var firstArray = [];
var secondArray = [];

arr.forEach(function(item) {
  var split = item.split("[");
  firstArray.push(split[0]);
  secondArray.push(split[1].slice(0,-1));
});

console.log(JSON.stringify(firstArray));
console.log(JSON.stringify(secondArray));

Comments

0

You could use a regular expression and separate the wanted parts.

var array = ["text1[483]", "text 2[411]", "text 3[560]", "text[484]"],
    texts = [],
    numbers = [];

array.forEach(function (a) {
    var m = a.match(/^(.*)\[(.*)\]$/);
    texts.push(m[1]);
    numbers.push(m[2]);    
});

console.log(texts);
console.log(numbers);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.