Beginning and end pairs in array - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of Number / String literals and returns another array of arrays. With each subarray containing exactly two elements, the nth element from start nth from last.

For example −

If the array is −

const arr = [1, 2, 3, 4, 5, 6];

Then the output should be −

const output = [[1, 6], [2, 5], [3, 4]];

Example

Following is the code −

const arr = [1, 2, 3, 4, 5, 6];
const edgePairs = arr => {
   const res = [];
   const upto = arr.length % 2 === 0 ? arr.length / 2 : arr.length / 2 - 1;
   for(let i = 0; i < upto; i++){
      res.push([arr[i], arr[arr.length-1-i]]);
   };
   if(arr.length % 2 !== 0){
      res.push([arr[Math.floor(arr.length / 2)]]);
   };
   return res;
};
console.log(edgePairs(arr));

Output

Following is the output in the console −

[ [ 1, 6 ], [ 2, 5 ], [ 3, 4 ] ]
raja
Published on 18-Sep-2020 08:51:03
Advertisements