Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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
]
];
Understanding Sparse Arrays
A sparse array is an array where most elements are empty or undefined. JavaScript handles sparse arrays efficiently by only storing non-empty elements, which saves memory for large arrays with few values.
Implementation
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 ]
]
How It Works
The function iterates through each coordinate pair in the input array. For each pair [row, col], it:
- Creates a sub-array at
res[row]if it doesn't exist - Sets
res[row][col] = 1to mark that position - Leaves all other positions as empty slots in the sparse array
Alternative Approach with Array Constructor
Here's another way to create the sparse array with explicit undefined values:
const createDenseArray = (arr = []) => {
let maxRow = Math.max(...arr.map(el => el[0]));
let result = [];
for (let i = 0; i <= maxRow; i++) {
let rowData = arr.filter(el => el[0] === i);
if (rowData.length > 0) {
let maxCol = Math.max(...rowData.map(el => el[1]));
result[i] = new Array(maxCol + 1).fill(undefined);
rowData.forEach(el => {
result[i][el[1]] = 1;
});
} else {
result[i] = undefined;
}
}
return result;
};
const arr2 = [[3, 1], [2, 12], [3, 3]];
console.log(createDenseArray(arr2));
[
undefined,
undefined,
[
undefined, undefined, undefined, undefined, undefined,
undefined, undefined, undefined, undefined, undefined,
undefined, undefined, 1
],
[ undefined, 1, undefined, 1 ]
]
Conclusion
Converting 2D coordinates to sparse arrays is useful for representing coordinate-based data efficiently. The sparse approach saves memory by only storing actual values, while the dense approach provides explicit undefined values for debugging purposes.
