Creating a fresh 2-dimensional array by extracting specific information from an existing array

If I have a scenario with a 2d array structured as follows:

[
  [0,1,4,2,2,5,5,0],
  [1,1,4,4,2,2,5,3],
  [1,6,6,6,7,7,3,3]
]

And if I want to create a new 2d array by abstracting the identical numbers like shown below: {any one of these}

[
  [0,1],
  [1,1],
  [1,0]
]

[
  [2,2,0],
  [0,2,2]
]

[
  [0,3],
  [3,3]
]

[
  [4,0],
  [4,4]
]

[
  [5,5],
  [0,5]
]

[
  [6,6,6]
]

How can I achieve this kind of logic in JavaScript? Essentially, I need a solution to generate one multidimensional array based on the duplication of numbers in the original 2d array.

Answer №1

// Initializing Data
const arr = [
  [0, 1, 4, 2, 2, 5, 5, 0],
  [1, 1, 4, 4, 2, 2, 5, 3],
  [1, 6, 6, 6, 7, 7, 3, 3],
];

// Define the numbers to distribute among isolated arrays
const numbersForDistribute = [1, 2, 3, 4, 5, 6, 7];

const result = [];

for (let n of numbersForDistribute) {

  // Find the range within the initial array for each number 
  // to determine the size of the result array for it 
  let minRowIndex = 999;
  let maxRowIndex = 0;

  let minColumnIndex = 999;
  let maxColumnIndex = 0;

  for (let i in arr) {
    const row = arr[i];

    for (let j in row) {
      const currentElement = row[j];

      if (row[j] === n) {
        if (i < minRowIndex) {
          minRowIndex = i;
        }

        if (i > maxRowIndex) {
          maxRowIndex = i;
        }

        if (j < minColumnIndex) {
          minColumnIndex = j;
        }

        if (j > maxColumnIndex) {
          maxColumnIndex = j;
        }
      }
    }
  }

  const resultForN = [];

  // Build the result array with a specific size for each number 
  for (let i = minRowIndex; i <= maxRowIndex; i++) {
    resultForN.push([]);
    for (let j = minColumnIndex; j <= maxColumnIndex; j++) {
      resultForN[resultForN.length - 1].push(arr[i][j] === n ? n : 0);
    }
  }

  result.push(resultForN);
}

console.log(result);
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}

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

Tips on refreshing a view in react as data updates

Currently, I am delving into learning a variety of subjects such as Typescript, Express, and my newfound interests in REACT and RXJS. To aid in my studies, I created a Quick-List on Github, but encountered a question... "How can the view in React be upda ...

What are the steps to creating a popup form on a website?

I am implementing LDAP bind authentication to password protect my page. The process and script are working fine. I have a form that submits to the script for user authentication. If the user lacks authentication, they are redirected. I want to turn the ex ...

Combining jQuery with AngularJS for optimal web development outcomes?

As someone new to AngularJS, this project is challenging my knowledge of ng-repeat and controllers. Objective : My goal is to have the guitars appear when an option is selected from the drop-down menu and the button is clicked using ng-repeat. Currently, ...

I am currently grappling with a JavaScript mouse over event and encountering some difficulties

I am looking to dynamically change the background image of my body div whenever a link is hovered over. Here is a snippet of my code: JAVASCRIPT: var i = 0, anchors = document.querySelectorAll("zoom"), background = document.getElementById("body") ...

Running an ESNext file from the terminal: A step-by-step guide

Recently, I delved into the world of TypeScript and developed an SDK. Here's a snippet from my .tsconfig file that outlines some of the settings: { "compilerOptions": { "moduleResolution": "node", "experimentalDecorators": true, "module ...

Is it possible to omit specific files from an NPM package during installation?

Is there a way to omit specific files from the list of NPM packages in my package.json? In my unique non-browser environment, every file within the node_modules directory automatically becomes part of the final production package. This means that there is ...

Instructions for adding a method to a prototype of a generic class in TypeScript

My current challenge involves adding a method to a prototype of PromiseLike<T>. Adding a method to the prototype of String was straightforward: declare global { interface String { handle(): void; } } String.prototype.handle = functi ...

Break up a list into separate paragraphs and style each word using individual CSS

I have a user-generated paragraph that consists of a list of words separated by commas, such as "dog, cat, hamster, turtle." I want to be able to individually assign attributes to each word in the list. Check out this image for reference In the example i ...

show a fresh new page using react router

I have recently developed a mobile app that showcases a collection of movies. Currently, it is static and I am looking to implement a react router for navigation. Specifically, I want the user to be directed to a detail page for a TV Show when they click o ...

Is there a gap in the Nativescript lifecycle with the onPause/onResume events missing? Should I be halting subscriptions when a page is navigated

My experience with NativeScript (currently using Angular on Android) has left me feeling like I might be overlooking something important. Whenever I navigate to a new route, I set up Observable Subscriptions to monitor data changes, navigation changes, an ...

Tips for testing a function that calls other functions during unit testing

Exploring jest for the first time to test my REST API has been quite the learning experience, especially when it comes to unit testing the controllers. I'm facing a challenge in testing a function that involves calls to other functions (including npm ...

Executing Two Distinct JQuery Api Requests

I'm facing a challenge with integrating the data from two different API calls and processing them together. After receiving JSON responses from both calls, I convert them into GeoJSON format. The next step is to combine these geojson objects in anothe ...

Ways to extract random elements from a variety of arrays

I'm looking for the best way to extract data from multiple arrays. Currently, I have: $array1 = ['A', 'B', 'C', 'D', 'E']; $array2 = ['Q', 'W', 'P', 'R', &apos ...

What is the best way to retrieve a variable's value using its reference?

Within my array called tags are the names of various restaurants. I am attempting to utilize this information within a for loop in the GMapMarker to access data based on the restaurant name. let tags[] = {name: 'mcdonalds', id: '1'}, {n ...

Error occurred due to a reference to a function being called before it was

Occasionally, I encounter a "Reference Error" (approximately once in every 200 attempts) with the code snippet below. var securityPrototype = { init: function(){ /* ... */ }, encryptionKey: function x() { var i = x.identifier; ...

Implement a jQuery slideshow with a full background image, aiming to set up a clickable link on the final image of the

Could someone please help me with a query I have regarding a background image slide show using jQuery code? I have set up a slide show with multiple images and would like to make the last image clickable. Is it possible to achieve this specific functionali ...

Guide on utilizing TypeScript interfaces or types in JavaScript functions with vscode and jsdocs

Is there a way to utilize types or interfaces to provide intellisense for entire functions or object literals, rather than just function parameters or inline @type's? For example: type TFunc = ( x: number ) => boolean; /** * @implements {TFunc} ...

The challenge of maintaining coherence in AngularJS scopes

It's driving me crazy. Our integration with some ATSs involves sending queries and setting variables in the scope upon receiving responses. I always make sure to set the variables within a $scope.$apply() to ensure proper updating. Everything was work ...

Using React to Dynamically Display JSON Data as HTML

Struggling to incorporate HTML rendering from JSON data into my React component without relying on dangerouslySetInnerHTML. I want to include other React components within the rendered HTML, but facing challenges when trying to render multiple elements or ...

Access the value retrieved from a form on the previous page using PHP

I'm struggling with extracting values from radio buttons on a previous page. Currently, my HTML and PHP code works fine with the search bar, which is the first form below. However, I'd like to add radio button filters below the search bar. <s ...