Update the multidimensional array function to ES6 syntax

I'm in the process of developing a function for my app and I'm curious if there's a more elegant way to implement it using ES6, without relying on two for loops.

The goal is to create a multi-dimensional array that keeps track of x and y coordinates. While the current implementation works effectively, I'm looking for a cleaner solution.

function createBoard() {
boardParts = new Array(tileCount);
for (let i = 0; i < tileCount; ++i) {
    boardParts[i] = new Array(tileCount);
    for (let j = 0; j < tileCount; ++j) {
        boardParts[i][j] = new Object();
        boardParts[i][j].x = tileCount - 1 - i;
        boardParts[i][j].y = tileCount - 1 - j;
    }
}
emptyLoc.x = boardParts[tileCount - 1][tileCount - 1].x;
emptyLoc.y = boardParts[tileCount - 1][tileCount - 1].y;
solved = false;
}

Any suggestions or guidance would be greatly appreciated!

Many thanks

Answer №1

To implement ES6, utilize the Array#from method for creating arrays:

const numTiles = 4;

const gridParts = Array.from({ length: numTiles }, (_, x) => 
  Array.from({ length: numTiles }, (_, y) => ({
    x: numTiles - 1 - x,
    y: numTiles - 1 - y
  }))
);

console.log(gridParts);

Answer №2

When it comes to improving code in ES2015+, there isn't much available other than Array.from (mentioned by Ori Drori on Stack Overflow). However, there are ways to enhance code that have been around since ES5. Take a look at the following suggestions:

function setBoard() {
    boardParts = []; 
                     
    for (let i = 0; i < tileCount; ++i) {
        boardParts[i] = []; 
        for (let j = 0; j < tileCount; ++j) {
            boardParts[i][j] = {           
                x: tileCount - 1 - i,      
                y: tileCount - 1 - j       
            };
        }
    }
    emptyLoc.x = boardParts[tileCount - 1][tileCount - 1].x;
    emptyLoc.y = boardParts[tileCount - 1][tileCount - 1].y;
    solved = false;
}

In addition, the function assumes that boardParts, tileCount, emptyLoc, and solved are already declared in the surrounding context. It's generally not recommended to have functions that heavily rely on side-effects without some form of object initialization...

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

I'm having trouble locating my route for some unknown reason

I've set up a basic code structure to test my routes, but I keep getting a 404 error. Although I have an app.all function to catch errors, I'm having trouble pinpointing where the issue lies. Below is my index.js file, where I've configured ...

How can I trigger an API call 30 seconds after my React Native app switches to the background?

Seeking assistance with my React Native app: I am trying to make an API call 30 seconds after the app goes into the background. I am using AppState from react-native to detect when the app goes into the background, but I'm not receiving any callback a ...

Image Animation Using a Rotational Control (HTML/JavaScript/...)

I am interested in achieving a specific effect with a series of images that transition from dark to light. My idea is to have a dial or slider underneath or over the frame so that when it is moved to the left, the black image is displayed, and when moved t ...

An error has occurred: Noty (notification library) is not defined in this AngularJS Web Application

I am currently diving into the world of AngularJS and building a web application from scratch. As a newbie to AngularJS, I want to point out that I might be missing something crucial. An issue has arisen: After installing the Noty library (npm install no ...

Difficulty with timing in React.js when rendering content from an Express.js API

I am facing a timing issue while working with React.js. My component checks the validity of the user's token and type. If the user is an admin, it should display certain content; otherwise, it should show "you don't have permission". However, I ...

Is there a way for me to retrieve form information?

I have encountered a challenge with my React app. The login form data appears to be empty when I attempt to send it to the backend. // Login component class submitLoginForm = (event) => { event.preventDefault(); const target = event.target; ...

The DOM assigned a new source to an image

Currently, I am working on a project that involves both jquery and PHP. In this project, users are able to upload images which are then displayed in blocks. The uploading functionality is already working, but I am facing an issue with setting the image sou ...

What is the reason behind this code's ability to detect vowels as well as other

I'm currently working on debugging a specific portion of code for my class. I'm having trouble understanding why this JavaScript code is counting all letters instead of just vowels. var text, i, sLength, myChar; var count; var text = prompt("Ple ...

Ways to circumvent ng switch and create a component based on type

In my current code, I have an array called resourceTypes and I am using ngSwitch to create different components/directives based on the TypeName. However, I find this approach cumbersome as I have to update the code every time I add a new resource editor. ...

Navigating between routes in NEXT JS involves passing state, which can be achieved through various

Within one of my page objects, I have some data that I need to send to another page when redirecting. The code snippet below shows how I achieved this: const redirectAppointmentStep1 = (value) => { router.push({ pathname: '/Appointment/bo ...

Having trouble launching the Socket.io Chat Demo? Encounter an issue with the error message at ..//

Hello, I am a novice in the world of programming and recently attempted to run the socket.io chat demo. Unfortunately, I encountered an error message at line 5 stating that it cannot find ('../..'). Can someone please shed some light on why this ...

How can I update data in Select2 after it has been initialized?

After initializing select2, I am trying to set an array of data in the following way: var selection = $('#selection').select2({}); selection.data([ {id: 1, text: 'value1'}, {id: 1, text: 'value1'} ]); However, I am encou ...

The array within the JSON object holds vital information [Typescript]

I have some data stored in an Excel file that I want to import into my database. The first step was exporting the file as a CSV and then parsing it into a JSON object. fname,lname,phone Terry,Doe,[123456789] Jane,Doe,[123456788, 123456787] Upon convertin ...

AngularJS: Issue with ngChange not being triggered from directive

A Summary of the Issue at Hand I've created a directive that dynamically displays a list of checkboxes. The directive has a parameter named options, which should be an array structured like this in order for the checkboxes to display correctly: var ...

Limit the radio button to being clickable

Ugh, I'm really struggling with this. I want to create a quiz where only the radio button is clickable, not the text itself. Can anyone help me figure out how to do this? I have two codes below that I don't quite understand. I'll include th ...

The issue arises with getInitialProps as it fails to pass data to the page component while attempting to retrieve initial information and subsequently modify it using a button

I am currently working on a component located at app\page.tsx in Next.js v13.4.12, and it includes a button. My goal is to have the button trigger the handleClick function when clicked. The issue I'm facing is that the getInitialProps function ...

Best practices for transferring data in node.js (unresolved)

Is it possible to pipe a file from an external server through localhost using Node.JS? (Imagine loading localhost as if it were another site like ) Here is the scenario: A PC requests http://localhost:80/highres/switch.html The Node application then ...

Utilizing the Jquery ready method in conjunction with the load function

While utilizing the ready() method to access the DOM, I encountered an issue where jQuery was returning undefined when trying to access an element. Even after nesting the ready() function inside $(window).on("load", function()), there were still instances ...

Error: The object 'exports' is not defined in geotiff.js at line 3

Looking to integrate the geotiff library with Angular 6.1.0 and TypeScript 2.9.2. Installed it using npm i geotiff Encountering the following error in the browser console: Uncaught ReferenceError: exports is not defined at geotiff.js:3 After r ...

Tips on utilizing useStyle with ReactJS Material UI?

Is there a way to utilize a custom CSS file in the useStyle function of Material UI? I have created a separate useStyle file and would like to incorporate its styles. Can someone explain how this can be accomplished? input[type="checkbox"], inp ...