Combine an array of arrays with its elements reversed within the same array

I am working with an array of numbers that is structured like this:

const arrayOfArrays: number[][] = [[1, 2], [1, 3]];

The desired outcome is to have [[1, 2], [2, 1], [1, 3], [3, 1]].

I found a solution using the following approach:

// initialize an empty array
let result: number[][] = [];

for (const elArr of arrayOfArrays) {
    result.push(elArr);
    result.push(elArr.reverse());
}

However, I believe there might be more elegant ways to achieve this. Any suggestions?

Answer №1

To achieve this, you can utilize the Array#flatMap method to obtain the desired outcome within a single iteration.

var matrix = [[1, 2], [1, 3]],
    output = matrix.flatMap(([...data]) => [[...data], data.reverse()]);

console.log(output);

Answer №2

Although your solution is clever, I decided to try a different approach:

let array = [[1, 2], [1, 3]];

let transformedArray = array.map((value, index) => {
    return [value, array[index].slice().reverse()];
}).flat();

Keep in mind that Array.flat() is a new feature, so feel free to refer to the ES specification here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to establishing a primary filter for my Json information with Angular.js?

After spending multiple days searching and reading, I am struggling to set an initial value for the data from a Rails JSON file in my application. The app focuses on incident tickets, and although I am able to retrieve all entries from the database using d ...

Internet Explorer failing to trigger Ajax requests

I'm encountering an issue with my script on my webpage - it works perfectly in Chrome, but Internet Explorer is not entering the success{} function of Ajax. It does go into the Complete{} function without any problems. I attempted to pass the data var ...

With the use of discreet JavaScript, the parameter is not empty; instead, it contains values

Previously, my JavaScript code was functioning correctly when it was within the same page as my cshtml file: function SaveEntity() { // more code here alert(entity.FirstName); /* this shows that entity's properties have values */ $.post( ...

What is the best method for effectively eliminating duplicate objects with the same value from an array?

Let's say we have a collection of jqlite objects, and using the angular.equals function, we can determine if they are equal. How can we utilize this function to eliminate duplicate items from an array of jQlite objects? This is my attempted solution: ...

Ways to structure this updateone query for mongoose formatting

UPDATE: After making adjustments to the query using arrayFilters recommended by someone here, the query is returning success. However, the values in the database are not being updated. I am attempting to update specific fields within a MongoDB collection ...

Encountered a TypeError in React 16.7: The function (0, _react.useState) is not recognized

Error: TypeError: (0 , _react.useState) is not a function React versions currently being used: "react": "^16.7", "react-dom": "^16.7", File src/App.js: import {memo, useState} from 'react' export default memo(() => { useS ...

Deliver router services for central Angular 2 elements

I am working on an ng2 app where I have the app/app.module and core/core.module. In the core modules, there are some modules that are used at the app top level and only once as mentioned in the official documentation. However, one of these modules requires ...

Which is better: storing an element in a variable or selecting it every time it's needed for efficiency?

When targeting an element multiple times, which method is more efficient? Consider Example 1: var el = $("#element"); el.html("foo"); el.html("bar"); Compare it to Example 2: $("#element").html("foo"); $("#element").html("bar"); Is there a noticeable ...

Node.js Export Module Error - importance of separating concerns

I have been attempting to implement separation of concerns by using export module. Everything functions properly when used without separating concerns, but as soon as I try to import generateUrlArray() from const db = require('../db'), nothing se ...

Tips for loading images dynamically (or lazily) as they come into the user's view with scrolling

Many modern websites, such as Facebook and Google Image Search, display images below the fold only when a user scrolls down the page enough to bring them into view (even though the page source code shows X number of <img> tags, they are not initially ...

What is the jQuery alternative for the classList property in vanilla JavaScript?

Currently, I am working on a collaborative project with two acquaintances. One of the requirements is to stick to either vanilla JavaScript selectors like document.getElementById("thisDiv"); or jQuery selectors such as $("#thisDiv"); to maintain consis ...

Navigating using Backbone Marionette URL to Server Endpoint

I need to implement client-side validation to check if the user is logged in, and if not, redirect them to the sign-in page. The issue is that the sign-in page exists outside of my Backbone Marionette app. Is there a way in Marionette, Backbone, jQuery, or ...

Navigating with Anchors, Styling and jQuery

Firstly: Apologies in advance for any language errors as English is not my native tongue. :) The Scenario Here's the deal: I'm attempting to create a single button that, when clicked by the user, automatically scrolls down to the next DIV. Each ...

Mapping JSON to interface in Angular 7: A step-by-step guide

I am currently working with angular7 and I have a requirement to map a json object to my interface. My goal is to create a function that can accurately map the fields of the json object to the corresponding properties in the interface. Additionally, if the ...

What is the best way to access a variable from a class in ES6?

Hey there, I'm having trouble accessing the variable from the KeyCodeClass. Let me walk you through what I've tried so far: Attempt 1 class KeyCodeClass1 { constructor() { this.space; } KeyDown(e) { if (e.keyCode == 3 ...

modifying the state in a stateless React component

Hello everyone! I am here trying to work with hooks and I'm not sure how to achieve my goal. Here is the code I have: import React, { useState } from 'react' import { useForm } from 'react-hook-form' import {useDispatch } from &a ...

Different techniques for retrieving elements generated by ng-repeat from their containing parent

Let's keep it simple - imagine we have a directive called headSlides. This directive's template includes an image that is being repeated using ng-repeat: <img class="bg" ng-repeat="image in images" ng-src="{{image.src}}"> I need to access ...

Navigating to a new page once a backend function in Express has finished executing

Recently, I have been experimenting with express web servers to create a website that allows users to sign in using Discord's OAuth2 API. In order to secure sensitive information, I have been utilizing the express-session npm module to store data with ...

Creating a replicated Dropdown menu with Jquery and inserting it into a changing Div

I currently have a dropdown list on my page with the ID of "mainDDL" and some pre-existing data. Now, I am looking to duplicate this dropdown list and add it to another specific div element. To accomplish this, I used the following code snippet: var dd ...

understanding the life cycle of components in Ionic

I created a component with the following structure: export class AcknowledgementComponent implements AfterViewInit { private description: string; @Input('period') period: string; constructor() { } ngAfterViewInit() { console.log ...