 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Beginning and end pairs in array - JavaScript
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 ] ]
Advertisements
 