Oh my goodness, you've just opened up a whole can of worms.
In the realm of Javascript, arrays are considered a special type of object. Similar to all other Javascript objects, they have the ability to contain arbitrary string properties:
const exampleArray = [];
exampleArray["key"] = "value";
However, it's important to note that this string property is attached to the array object itself and not treated as an actual item within the array:
exampleArray.forEach(console.log); // does not log anything
Despite this, you can still access the property just like any other object property:
console.log(exampleArray["key"]); // "value"
Yet, it won't be recognized in typical iteration methods such as C-style for loops or the map/forEach functions for arrays.
The line in your code snippet:
array["3"] = "this should not be the first element";
represents a different scenario. Due to Javascript's loose handling of type conversions, this actually assigns the string to the 4th position in the array:
const anotherArray = [];
anotherArray["3"] = "oops!"; // equivalent to anotherArray[3] = "oops!"
console.log(anotherArray); // [empty x 3, "oops!"]
This aspect can be advantageous (apart from the implicit conversion) especially when dealing with sparse arrays which JavaScript supports. The iteration will only yield the single element:
anotherArray.forEach((item, index) => console.log(item, index)); // ["oops", 3]
It's worth noting that despite there being no preceding elements, the string does hold the correct index of 3 and remains accessible through that index:
anotherArray[3]; // "oops"
Essentially, the initial two assignments in your sample code create properties on the array object while the third one adds an actual item to the array at the 4th index (with nothing occupying the first 3).
If you are aiming for ordered data as suggested by Reese Casey, opting for a plain object may be more suitable:
const newObject = {}; // curly braces
newObject["some key"] = "whatever";
That being said, the properties within an object are generally unordered. If specific ordering is vital, an array would be appropriate but ensure that all indexes are integers and sequentially placed. This can be achieved effortlessly using the .push method:
newArray = [];
newArray.push("something");
newArray.push("something else");
Thus, newArray will consist of two elements orderly positioned at index 0 and 1 respectively.
Additional Insight based on remark from the previous answer:
I want some of the data to be ordered, and the rest to follow suit
To accomplish this task, object destructuring comes into play:
const databaseResponse = {
desiredKeyOne: 3,
desiredKeyTwo: 2,
foo: 6,
bar: 7,
};
const {
desiredKeyOne,
desiredKeyTwo,
*remaining,
} = databaseResponse;
const outputData = [
desiredKeyOne,
desiredKeyTwo,
...Object.values(remaining),
]; // [3, 2, 6, 7]
Note that the structured content inserted into the array retains its order due to deliberate arrangement.