
- 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
Pairing an array from extreme ends in 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
The code for this will be −
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
The output in the console will be −
[ [ 1, 6 ], [ 2, 5 ], [ 3, 4 ] ]
- Related Articles
- Excluding extreme elements from average calculation in JavaScript
- Removing an element from an Array in Javascript
- Filter null from an array in JavaScript?
- Building an array from a string in JavaScript
- Select random values from an array in JavaScript?
- Picking out uniques from an array in JavaScript
- From JSON object to an array in JavaScript
- Constructing largest number from an array in JavaScript
- Finding matching pair from an array in JavaScript
- Get the smallest array from an array of arrays in JavaScript
- JavaScript creating an array from JSON data?
- Extract unique values from an array - JavaScript
- Filtering out primes from an array - JavaScript
- Pairing Heaps
- Completely removing duplicate items from an array in JavaScript

Advertisements