
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 ] ]
Advertisements