1

I Have array like this.

 var array= ["4220495|1", "4220495|2"]

I want these values in separate array like this

var firstArray=["4220495", "4220495"];
var secondArray=["1", "2"];

If you want more information let me know.

4 Answers 4

2

You can iterate over the values and get the result

var array= ["4220495|1", "4220495|2"];
var firstArray = [];
var secondArray = [];

for (var i = 0; i < array.length;i++) {
  var itemArray = array[i].split('|');
  firstArray.push(itemArray[0]);
  secondArray.push(itemArray[1])
}
console.log(firstArray);
console.log(secondArray);

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

Comments

2
var firstArr = [];
var secondArr = [];
["4220495|1", "4220495|2"].map(function(value) {
   var splitted = value.split('|');
   firstArr.push(splitted[0]);
   secondArr.push(splitted[1]);
});

Comments

2

Many ways to do this. Here's one:

var array= ["4220495|1", "4220495|2"];
var firstArray = array.map(function(v){ return v.split("|")[0] });
var secondArray= array.map(function(v){ return v.split("|")[1] });

1 Comment

The other solutions are more efficient, as they only require one iteration.
2

This is a more generic solution for any split length.

var array = ["4220495|1", "4220495|2"],
    firstArray = [],
    secondArray = [];

function arraySplit(array, target) {
    array.forEach(function (a) {
        a.split('|').forEach(function (b, i) {
            target[i].push(b);
        });
    });
}

arraySplit(array, [firstArray, secondArray]);

document.write('<pre>' + JSON.stringify(firstArray, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(secondArray, 0, 4) + '</pre>');

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.