Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to represent a sparse array in JSON?

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?

like image 701
Vilx- Avatar asked Nov 14 '09 08:11

Vilx-


People also ask

What is sparse array example?

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 is sparse array in JS?

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.

What is a sparse array in programming?

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.

What is the difference between dense and sparse arrays?

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.


1 Answers

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.

like image 175
Christian C. Salvadó Avatar answered Sep 20 '22 03:09

Christian C. Salvadó