I've got a sparse array that I want to represent in JSON. For example:
-10 => 100
-1 => 102
3 => 44
12 => -87
12345 => 0
How can I do this? Can I do this?
Arrays are labeled in ways that show their sequence – for example, in common computer language notation, an array of six variables named A(6) can hold values for A1, A2, A3, A4, A5 and A6. If more than three or four of these values are zero, the array is said to be “sparse.”
What are sparse arrays? A sparse array is one in which the elements are not sequential, and they don't always start at 0. They are essentially Array s with "holes", or gaps in the sequence of their indices. So an example would be: let array = []; array[100] = "Holes now exist"; array.
A sparse array programming language is an array programming language that supports element-wise application, reduction, and broadcasting of arbitrary functions over dense and sparse arrays with any fill value.
A matrix that has been compressed to eliminate zero-values is a sparse matrix, whereas a matrix with zero and nonzero values is a dense matrix.
You can represent it as a simple object:
{
"-10" : 100,
"-1" : 102,
"3" : 44,
"12" : -87,
"12345" : 0
}
Since it will be a simple object, you cannot iterate it the same way as an array, but you can use the for...in
statement:
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var value = obj[key];
}
}
And if you want to access an specific element by key, you can use also here the square bracket property accessor:
obj['-10']; // 100
Note that I use the hasOwnProperty
method inside the for...in
loop, this is to prevent iterating properties defined on higher levels of the prototype chain, which can cause problems and unexpected behavior... more info here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With