74058

Insert into array at non-existent index

Question:

I'm trying to format an array in javascript with data pulled from a database so that the ID of the row is the index of the array, so the data

ID | Data ---------------------------- 1 | hi 2 | more data 4 | junk data 8 | hello world 12 | h3ll0

would look like

array: [1] = hi [2] = more data [4] = junk data [9] = hello world [12] = h3ll0

i have tried using array.splice(id,1,data) but when i console.log the array the indexes don't match, almost as if because an index isn't exist before it just appends the value at the end of the array.

So i am wondering how i can go about adding data to an array at any index so i can create an array as shown in the example

Answer1:

Believe it or not, you just assign to it:

var a = []; // Creates array a[1] = "hi"; a[2] = "more data"; a[4] = "junk data"; a[9] = "hello world"; a[12] = "h3ll0";

This is because standard arrays in JavaScript <a href="http://blog.niftysnippets.org/2011/01/myth-of-arrays.html" rel="nofollow">aren't really arrays at all</a>, they're just objects with some special behavior. Array "entries" are just object properties. And in JavaScript, if you assign to an object property that doesn't exist yet, it gets created.

You only need an array for this if you plan to use array features, like length (which will be 13 in the above example; it's always one higher than the highest index, or it's the value you give it if you assign to length directly), or splice, etc. If you <em>don't</em> plan to use those features, you can just use an object (var a = {}; rather than var a = [];). Nothing else above changes.

Answer2:

Don't use an array this way - if you have one element at index 9 then indicies 0-8 will then <strong>be</strong> <del>have values of</del> undefined when you loop over it which can be very confusing, especially if you try to determine the length of your array.

What you want to do be using, is an object with numeric keys.

var x = {}; x.[id] = data;

Recommend

  • converting .string file format into php array format
  • Angularjs modal acting weird with checkboxes
  • Convert csv data to specific format DYNAMIC
  • JavaScript equivalent of the MySQL function SUBSTRING_INDEX()
  • Pandas multi-index subtract from value based on value in other column
  • Multiple for loop iterators to unpack in Python [duplicate]
  • Inno Setup Search for specifc file on a CD, retrieve exact filepath and return value to [Files]-Sect
  • How to use HTTP Authentication with PHP and then run the entered data against a database?
  • Publishing HTML Field Control Converts Relative URL to Absolute URL
  • angular infinite digest loop from ng-model using getterSetter
  • Number of nodes returned in MutationRecord.addedNodes nodelist (mutationObserver)
  • Recommended way to remove events on destroy with jQuery UI Widget Factory
  • Differences between drawing an Ellipse in Android and Java
  • Best way to produce 'colour correct' raster from a PDF or PS with ghostscript
  • In java, how do you retrieve images from a jar file?
  • Mongodb update() vs. findAndModify() performace
  • GitHub default README markup
  • Vigenere cipher not working
  • What is this strange character in chrome's resource css viewer?
  • How to repeat sections of a SQL query across UNIONs? (DRY in SQL)
  • pickle.PicklingError: args[0] from __newobj__ args has the wrong class with hadoop python
  • Using $compile in a directive triggers AngularJS infinite digest error
  • How to add a focus style to an editable ComboBox in WPF
  • How do I superscript characters in a UIButton?
  • Detect when Facebook like button is clicked
  • Needing to do .toArray() to get output of mongodb .find() on key name not value
  • Make VS2015 use angular-cli ng at build time in a .NET project
  • Is my CUDA kernel really runs on device or is being mistekenly executed by host in emulation?
  • Where to put my custom functions in Wordpress?
  • Can a Chrome extension content script make an jQuery AJAX request for an html file that is itself a
  • Upload files with Ajax and Jquery
  • How to pass list parameters for each object using Spring MVC?
  • How to delete a row from a dynamic generate table using jquery?
  • Python: how to group similar lists together in a list of lists?
  • json Serialization in asp
  • AngularJs get employee from factory
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • Proper way to use connect-multiparty with express.js?
  • Understanding cpu registers
  • How to stop GridView from loading again when I press back button?