
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Turning a 2D array into a sparse array of arrays in JavaScript
Suppose, we have a 2-D array like this −
const arr = [ [3, 1], [2, 12], [3, 3] ];
We are required to write a JavaScript function that takes in one such array.
The function should then create a new 2-D array that contains all elements initialized to undefined other than the element's index present in the input array.
Therefore, for the input array,
output[3][1] = 1; output[2][12] = 1; output[3][3] = 1;
And rest all elements should be initialized to undefined
Therefore, the final output should look like −
const output = [ undefined, undefined, [ undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, 1 ], [ undefined, 1, undefined, 1 ] ];
Example
The code for this will be −
const arr = [ [3, 1], [2, 12], [3, 3] ]; const map2D = (arr = []) => { const res = []; arr.forEach(el => { res[el[0]] = res[el[0]] || []; res[el[0]][el[1]] = 1; }); return res; }; console.log(map2D(arr));
Output
And the output in the console will be −
[ <2 empty items>, [ <12 empty items>, 1 ], [ <1 empty item>, 1, <1 empty item>, 1 ] ]
- Related Questions & Answers
- Flatten a 2d numpy array into 1d array in Python
- How to convert a 2D array into 1D array in C#?
- JavaScript Converting array of objects into object of arrays
- Split Array of items into N Arrays in JavaScript
- Converting array of arrays into an object in JavaScript
- JavaScript: Combine highest key values of multiple arrays into a single array
- How to add two arrays into a new array in JavaScript?
- How to sum elements at the same index in array of arrays into a single array? JavaScript
- Convert 2d tabular data entries into an array of objects in JavaScript
- Merge arrays into a new object array in Java
- How to store a 2d Array in another 2d Array in java?
- Counting the occurrences of JavaScript array elements and put in a new 2d array
- Array of objects to array of arrays in JavaScript
- Convert array into array of subarrays - JavaScript
- JavaScript: Converting a CSV string file to a 2D array of objects
Advertisements