
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 ] ]
- Related Articles
- Add elements at beginning and end of LinkedList in Java
- Get beginning and end date from a specific year in MySQL
- Finding peculiar pairs in array in JavaScript
- How to add new array elements at the beginning of an array in JavaScript?
- Swap certain element from end and start of array - JavaScript
- Java Program to get the beginning and end date of the week
- Unique pairs in array that forms palindrome words in JavaScript
- Java Program to remove whitespace from the beginning and end of a string
- How to convert nested array pairs to objects in an array in JavaScript ?
- How to move multiple elements to the beginning of the array in JavaScript?
- Shifting certain elements to the end of array JavaScript
- Adding an element at the end of the array in Javascript
- Removing an element from the end of the array in Javascript
- Moving all zeroes present in the array to the end in JavaScript
- Count of pairs in an array that have consecutive numbers using JavaScript

Advertisements