Home > Software engineering >  How to split an array in half and swap the second parts of elements with first part of elements
How to split an array in half and swap the second parts of elements with first part of elements

Time:12-22

Possibly with loop for in javascript and not methods

here my specs for the exercise :

Write a function called Swapper() that takes in input as a parameter an array and, after exchanging the first and second halves, return to the caller the modified array. Example

input: [5, 11, 1, 44, 2, 43]
output: [44, 2, 43, 5, 11, 1]

If the array has odd length, the center value must remain unchanged in place.

CodePudding user response:

You can use array.splice method to split an array in half and store the result in a temporary variavble and than use spread operator to combine both the arrays into a single one.
    
    let a = [1,2,3,4,5,6];
    let temp = a.splice(0,a.length/2);
    let splitted = [...a , ...temp];
    console.log(splitted)

CodePudding user response:

Check this out

const sample = [5, 11, 1, 44, 2, 43];

if(len%2==0)  var split = sample.length / 2;
else  var split = (sample.length   1)/2;

var arr1 = sample.slice(0,split);
var arr2 = sample.slice(split, sample.length);
[arr1, arr2] = [arr2, arr1]
const arr = [arr1,arr2];
  • Related