陣列中的首尾對 - JavaScript
我們需要編寫一個 JavaScript 函式,該函式接受一個數字/字串字面量的陣列,並返回另一個數組陣列。每個子陣列包含從開始到從結尾數第 n 個元素。
例如 −
如果陣列是 −
const arr = [1, 2, 3, 4, 5, 6];
則輸出應為 −
const output = [[1, 6], [2, 5], [3, 4]];
示例
以下為程式碼 −
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));輸出
以下為控制檯中的輸出 −
[ [ 1, 6 ], [ 2, 5 ], [ 3, 4 ] ]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP