Converting a two-dimensional array into a collection of sparse arrays

How can I transform the array x=[[3,1],[2,2]] into x[3][1]=1 and x[2][2]=1? Is there a way to make this code functional for arrays such as x=[[3,1],[2,12],[3,3]]?

Answer №1

Given that you have two variables to input: pos0, pos1

for (i in x)  
    if (x[i][0] == pos0 && x[i][1] == pos1) {
        // Perform actions
    }

This code snippet essentially verifies each index

Answer №2

If you haven't already, one approach is to iterate through and generate a new array. Then, set the value at the specified index.

This method involves creating a fresh array to store the final output.

var arr = [[3, 1], [2, 12], [3, 3]],
    resultArr = [];

arr.forEach(function (item) {
    resultArr[item[0]] = resultArr[item[0]] || [];
    resultArr[item[0]][item[1]] = 1;
});

console.log(resultArr);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

Here is a suggested approach:

let array = [[5,1],[2,20],[5,4]];
let result = array.reduce((previous, current) => {
  if (previous[current[0]]) {
    previous[current[0]][current[1]] = 1;
  } else {
    previous[current[0]] = Array.from({[current[1]]: 1, length: current[1]+1});
  }
  return previous;
}, []);
console.log(result);

Answer №4

let arr = [[3, 1], [2, 2]]

console.log('arr =', arr)

// Creating a sparse array
let sparseArr = []
for (let index in arr) {
  // Checking and initializing the inner array
  sparseArr[arr[index][0]] = sparseArr[arr[index][0]] || []
  // Setting value to the sparse array
  sparseArr[arr[index][0]][arr[index][1]] = 1
}

console.log('sparseArr =', sparseArr)

Output:

arr = [ [ 3, 1 ], [ 2, 2 ] ]
sparseArr = [ , , [ , , 1 ], [ , 1 ] ]

Answer №5

To cycle through the array and verify if there is an array corresponding to the first value, you can utilize array#reduce. If not found, initialize it with [], then assign the value to that specific index.

var x=[[3,1],[2,12],[3,3]];
var result = x.reduce((r,[a,b]) => {
  r[a] = r[a] || [];
  r[a][b] = 1;
  return r;
},[]);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Troubleshooting issues with cross-domain jQuery ajax requests

Struggling with this code and unable to make it work. This call consistently returns a "Failed to load resource: the server responded with a status of 401 (Unauthorized)" error message. $('#btnZendesk').click(function () { $.ajax({ ...

Solution: Resolve clientY scrolling issue within an HTML document

I am facing an issue with the positioning of my context menu. When I right-click and scroll down, the menu does not maintain its regular position. Instead of appearing to the right of the mouse cursor when stationary, it moves below the cursor based on how ...

Effective implementation of the useReducer hook across various React components to manage form state

My current project is proving to be quite challenging as I navigate through the step-by-step instructions provided. Initially, I was tasked with creating a BookingForm.js component that houses a form for my app. The requirement was to utilize the "useEffec ...

I'm struggling to understand why the `Logger` class isn't available during my exploration of a JavaScript Mixin pattern guide

Currently, I am delving into the world of programming and stumbled upon this tutorial. While following along, I encountered an issue in the console displaying the error message ReferenceError: Logger is not defined --> }(Logger)). It seems that the disc ...

What is the best way to change the "MuiPaper-elevation1" attribute in a Card element within Material-UI?

My Card component in HTML looks like this: <div class="MuiPaper-root MuiCard-root makeStyles-Card-5 MuiPaper-elevation1 MuiPaper-rounded"> I want to change MuiPaper-elevation1 to MuiPaper-elevation0 to remove the shadow. I attempted: ...

Switching Perspective on Live ExpressJS Path -- Node.JS

I previously set up an express route with a template. Here's the code: app.get('/route', function route(req, res) { db.get('db_ID', function compileAndRender(err, doc) { var stream = mu.compileAndRender('theme-file.e ...

The button designed to delete the parent container div is ineffective when applied to dynamically generated divs

I'm in the process of developing a JavaScript to-do list app from scratch. Everything is functioning properly except for the button that is supposed to remove items from the list. Here is the HTML snippet: <div class="todolistcontainer"& ...

Experiencing excessive CPU usage while utilizing a progress bar in Angular

Whenever I try to load a page with 2 progress bars, my CPU usage goes through the roof... I decided to investigate and found that once I removed them, the site's speed improved significantly. Here's a code snippet of one of the progress bars: ...

Updating information without the need for a page refresh

My project involves text boxes and drop-down menus where users input data, then click "generate" to combine the text from the boxes and display the result on the page. I'm struggling with clearing these results if the user clicks generate again, for ...

Angular 6 - Patience is key when waiting for an element to load within *ngIf after toggling ngIf to true

I have recently upgraded to angular 6. My HTML code is as follows: <div class="catalog-menus-subnav-wrapper" *ngIf="showMenus"> <div class="hidden-elem"> </div> </div> In this code snippet, the showMenus va ...

Invoking a function means calling another one simultaneously

There are two buttons in my code: The button on the right triggers a function called update(): <script> function update(buttonid){ document.getElementById(buttonid).disabled = true; event.stopPropagation(); var textboxid = buttonid.sli ...

Converting flat data into a nested object using JavaScript

Exploring the realms of react/ES6, I encountered an intriguing anomaly while utilizing the reduce method to convert a flat array received from an API into a nested object structure. Although I was well-versed in map and filter functions, the concept of red ...

Issue with onDblClick event in Angular5 and PrimeNG's p-listbox

I encountered an issue while using p-listbox's onDblClick event as it does not return the selected list element. Instead, the event object only contains the value of 'this'. {"originalEvent":{"isTrusted":true}} HTML Blockquote <!-- S ...

Enable form submission using the ENTER key when the focus is outside of an input field

Within my form, I have a div element that is focusable using tabindex="0". While this setup works well overall, I am facing an issue with submitting the form using the enter key. The submission works when an input field is in focus but not when the div has ...

Printing Multiple Pages Using JavaScript and Cascading Style Sheets

Encountering difficulties displaying page numbers when printing multiple multipage reports Here is the provided HTML Format : <style type="text/css> body { counter-reset: report 1 page 0; } td.footer:after { counter-increment: page; content ...

You can use the following code to retrieve the value of the checked radio button with the name "nameOfradio", but make sure that the radio button

I am attempting to extract the value from a radio button using the following code: document.querySelector('input[name=nameOfradio]:checked').value; However, I would also like to retrieve a value even if none of the radio buttons are checked. Fo ...

Generating a string indicating the range of days chosen

Imagine a scenario where there is a selection of days available to the user (they can choose multiple). The list includes Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday, each with an associated number from 0 to 6. For instance, Sunday ...

Creating a variety of NextJS components

Currently delving into NextJS and aiming to showcase a website featuring my various projects created with it. A special "Tag" component functions as a button template that allows custom text passed through props: export default function Tag({val}) { r ...

Select the final word and enclose it within a span class

I have a task where I need to identify the last word in a class and then enclose it with a span element so that I can style it using JavaScript. <h1 class="title>A long tile</h1> <h2 class="title>A long tile</h2> should b ...

Issue with the dropdown functionality in an Angular reactive form

I am experiencing an issue with a select dropdown in my Angular project. I have implemented a reactive form, but the dropdown is not functioning as expected and I am unsure of how to resolve this issue. Could someone offer assistance or guidance on how to ...