const traverseArray = function (arr) {
let res = [];
const getOutlineEl = (restArr, res) => {
res.push(...restArr.shift());
for (let i = 0; i < restArr.length; i++) {
res.push(restArr[i].pop())
}
res.push(...restArr.pop().reverse())
for (let i = restArr.length - 1; i >= 0; i--) {
res.push(restArr[i].shift());
}
if (restArr.length) {
return getOutlineEl(restArr, res)
} else {
return res;
}
}
return getOutlineEl(arr, res);
}
const length = 4;
const testArr = Array.from(new Array(length)).map((_, index) => Array.from(new Array(length)).map((_, insideIndex) => length * index + insideIndex + 1));
console.log(testArr);
console.log(traverseArray(testArr));
console