I have an array of numbers that looks like this:
const arrayOfArrays: number[][] = [[1, 2], [1, 3]];
What I need to get is [[1, 2], [2, 1], [1, 3], [3, 1]]
.
Apparently this can be achieved in the following way:
// create an empty array
let result: number[][] = [];
for (const elArr of arrayOfArrays) {
result.push(elArr);
result.push(elArr.reverse());
}
But there must be some more elegant ways to do this?
You could use Array#flatMap
and get the result in a single loop.
var array = [[1, 2], [1, 3]],
result = array.flatMap(([...a]) => [[...a], a.reverse()]);
console.log(result);
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加