Miguel Flores Miguel Flores - 1 month ago 17
Javascript Question

Split array in 2 parts

I'm trying to split an array of n elements (the array elements number always can be divided in 2), for example I have an array with 20 elements, right now I'm able to split

the first 10 elements and show it
but I don't have any idea of how to split the next 10 elements, here is my code to see more or less what I'm trying to do:



var array = "1, 5, 4, 3, 2, 6, 7, 8, 6, 55, 4, 33, 67, 7, 65, 45, 34, 32, 12, 23";
var array1 = [];
var array2 = [];

$(document).ready(function() {
$('#btn').click(function() {
magic();
});
});

function magic() {
var split;
var data = array.split(",");
var total = data.length;

for (var i = 0; i < total / 2; i++) {
array1.push(data[i]);
}

$('#a1').text(array1);

}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">Magic!</button>

<div>
<h4>Array 1</h4>
<p id="a1"></p>
</div>

<hr>

<div>
<h4>Array 1</h4>
<p id="a2"></p>
</div>





If you see my code the array 2 elements must be:


4, 33, 67, 7, 65, 45, 34, 32, 12, 23


What should I do to do this? In other words, if I have 50 elements I want to fill
array 1
with the first 25 elements and
array 2
with the rest of the elements. Thanks in advance for any help!

Answer

You could use Array#slice

var array = "1, 5, 4, 3, 2, 6, 7, 8, 6, 55, 4, 33, 67, 7, 65, 45, 34, 32, 12, 23";

$(document).ready(function() {
  $('#btn').click(function() {
    magic();
  });
});

function magic() {
  $('#a1').text(array.slice(0, array.length / 2));
  $('#a2').text(array.slice(array.length / 2));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">Magic!</button>
<div>
  <h4>Array 1</h4>
  <p id="a1"></p>
</div>
<hr>
<div>
  <h4>Array 1</h4>
  <p id="a2"></p>
</div>

Comments