JavaScript assoc array add key value pairs unexpected result - javascript

This is probably entirely obvious, but why am I not getting the expected JSON string when adding a key-value pair to this JavaScript array?
Next step: As code reveals, I actually wish to have two data sets in the object.
jsFiddle here - Weird, at the moment it only "works" in Chrome
var myKey = "123", myVal="Car";
var arrSummat = new Array();
$('#mybutt').click(function(){
arrSummat["987"] = "Boat";
//arrSummat[myKey] = myVal;
var test = JSON.stringify(arrSummat);
alert(test);
});

In JavaScript building an associative array* or hash map or object may not be terribly obvious. For one, everything is ultimately an object and so the syntax used with associative arrays is valid on everything that isn't an "associate array" which is probably where the confusion arises. First let's address the issue at hand. You probably wanted to use an object instead of an array:
arrSummat = {};
arrSummat["987"] = "Boat";
console.log(JSON.stringify(arrSummat)); // => {"987":"Boat"}
When running your fiddle (in Chrome) I pretty much get an array with 986 null values and then "Boat" (I may be wrong, I'm not hand counting the nulls in that alert).
Now that you're original question is resolved I'd like to point out two things you may want to start doing differently:
Prefer shorthand syntax for objects and arrays. The two examples are functionally the same but you should prefer the second for most purposes.
var myArr = new Array();
var myObj = new Object();
Is the same as:
var myArr = [];
var myObj = {};
The shorthand can even come with some basic values:
var myArr = [1, 2, 3];
var myObj = {one: "1", two: "2"};
Secondly, never use an Array object as anything other than an array. It is syntactically valid to do so but it will produce unexpected results (as you have seen here).
There is no "associative array" in JavaScript, but Objects are commonly used as a substitute and provide similar functionality.
Revised jsFiddle Link

Related

Forcing string representation of an array key

I am trying to maintain the order of an array with mixed key types. The array contains mostly keys represented by string values -- but if you enter a numbered key it goes to the front. How can I force a key which is a number to be a string type?
E.g.
array = [];
array["one"] = "some data";
array["two"] = "some more data";
array["3"] = "this should not be the first element";
How can I make "3" a string type to prevent it from moving to the top of the index?
Oh wow did you ever open multiple cans of worms.
Javascript arrays are a special type of Javascript objects, and like all Javascript objects they can have arbitrary string properties:
const foo = [];
foo["bar"] = "hi";
However that string is a property of the array object, not an item in the array:
foo.forEach(console.log); // logs nothing
You can still access it like any other object property:
console.log(foo["bar"]); // "hi"
But it won't show up in the usual iterative constructs like c-style for loops or the map/forEach array methods.
The line in your example
array["3"] = "this should not be the first element";
is very different however, because of Javascript's playing fast and loose with type conversions this actually sets the string to the 4th slot in the array:
const bar = [];
bar["3"] = "oops!"; // equivalent to bar[3] = "oops!"
console.log(bar); // [empty x 3, "oops!"]
This piece of it is actually a good thing (other than the implicit conversion part) rather than a problem: sometimes you need a sparse array and JS supports those. Iterating it will only produce the one element:
bar.forEach((item, index) => console.log(item, index)); // ["oops", 3]
Note though that the string has the correct index of 3, and can be accessed that way even though there's nothing "in front" of it:
bar[3]; // "oops"
So the first two assignments in your example create properties on the array object, and the third assignment is the only one that actually adds an item to the array, at the 4th index (there's nothing at the first 3).
What you seem to want as Reese Casey suggests, is a plain object:
const foo = {}; // curly
foo["some string"] = "whatever";
However now the properties are basically unordered. If you want them to be in a guaranteed specific order you do want an array, but all your indicies will need to be integers, and should be sequential. You can achieve this easily by using the .push method:
foo = [];
foo.push("something");
foo.push("something else");
Now foo will have two elements, in the correct order, and index 0 and 1 respectively.
Update based on comment on the other answer:
I want some of the data to be ordered, and the rest of the data to follow
This can be accomplished through object destructuring:
const responseFromDB = {
oneKeyICareAbout: 3,
anotherKeyICareAbout: 2,
foo: 6,
bar: 7,
};
const {
oneKeyICareAbout,
anotherKeyICareAbout,
*rest,
} = responseFromDB;
const stuffToDisplay = [
oneKeyICareAbout,
anotherKeyICareAbout,
...Object.values(rest),
]; // [3, 2, 6, 7]
And at least the destructured stuff you put in the array will be ordered because by doing so you've ordered it.
Javascript arrays cannot have string indexes. This is actually working incorrectly as the index is adding a property to the array object.
Changing to an object makes more sense for this.
EDIT: Whilst below its mentioned you can have string indexes you are not actually using the array by doing so. The answer by Jared Smith goes into much more detail as to why.
The other answers explain what is happening with your array-object mixture. For having an indexable thing which can reproduce the original order, you can use a Map:
The Map object holds key-value pairs and remembers the original insertion order of the keys.
array = new Map();
array.set("one","some data");
array.set("two","some more data");
array.set("3","this should not be the first element");
console.log("Test of get:",array.get("two"));
console.log("Test of order:");
for(let entry of array)
console.log(entry);

What's an Associative Array?

I'm trying to understand what an associative array really is and what steps are needed to acquire one. I have seen many explanations that are totally different.
I have tried testing it out on my own but can't seem to really get it in the end.
var array = ["one", "two", "three"];
var test = array["one"];
console.log(test);
I expected for it to target the index in which the string "one" is in, but an error occurs.
You are likely looking for a JavaScript Object, what is basically the same as an associative array, dictionary, or map in other languages: It maps strings to values. Unlike Arrays, which use square brackets [] for declaration, Objects use curly braces {} (please note that there are some exceptions).
Try to think of an Object as an associative array:
const arr = {one: 1, two: 2, three: 3};
console.log(arr['one']);
console.log(arr.one);
It is worth noting that Array's in JavaScript are technically objects.
The JavaScript Array object is a global object that is used in the construction of arrays; which are high-level, list-like objects.
The main difference between Array's and Object's is that Arrays are numerically indexed.
const arr = ['fooValue', 'barValue'];
const obj = {foo: 'fooValue', bar: 'barValue'};
console.log('arr: ', arr[0], arr[1]);
console.log('obj: ', obj.foo, obj.bar);
It is worth noting, that unlike primitive types in JavaScript, Object's (and Array's, which are also Object's) are passed by reference, so extra care is needed when attempting to copy the object.
function test(obj) {
obj['oops'] = 'this will modify the object';
}
const obj = {one: 1, two: 2, three: 3};
test(obj);
console.log(obj); // Object was updated
To avoid accidentally mutating your object, you will have to create a new instance of the object before performing operations on it. There are multiple ways to accomplish this:
Destructuring/spreading you object let obj2 = {...obj};
Using Object.assign()
I'm trying to understand what an associative array really is...
JavaScript doesn't have associative arrays in the sense that, for instance, PHP does. JavaScript has:
Arrays, which are (effectively) numerically indexed (see my blog post for why I said "effectively")
Objects, which are collections of properties that have names, which are either strings or Symbols (and which have other features, like inheritance)
Maps, which are collections of key/value pairs where the keys can be any type (not just strings or Symbols)
Arrays
To find the index of an entry in an array, typically you use indexOf (for an === match) or findIndex if you want to provide a predicate function.
var array = ["one", "two", "three"];
console.log(array.indexOf("one")); // 0
Objects
If you wanted, you could create an object that mapped strings to numbers:
var obj = {"one": 1, "two": 2, "forty-two": 42};
console.log(obj["forty-two"]); // 42
Maps
Similarly, a Map could do that:
var map = new Map([
["one", 1],
["two", 2],
["forty-two", 42]
]);
console.log(map.get("forty-two")); // 42
Associative arrays are used to associate something throughout an array.
You can use this with the query string for example:
In order to attain the information from a forum submitted, you need to put the user data into an associative array.
You would start by getting the query string as follows:
var queryString = window.location.search;
queryString = queryString.substring(1);
The reason why I did substring(1) is so we could remove the '?' at the beginning.
Once you have the query string of the website, you'd need a loop to separate the values of data received:
while (queryString.indexOf("+") != -1)
queryString = queryString("+", " ");
This will replace all the '+' signs in the string to spaces, making you get the values without the '+' signs. You'll have "Name=John" for example.
Now we need to split the '&'s from the string.
We also need to make an array ready for the data from the user.
var array = queryString.split("&");
var userData = [];
Afterwards, make a for loop in order to target however amount of data submitted and to attain it individually while storing it into the array:
for (let x = 0; x < array.length; x++)
{
var equalSign = array[x].search("=");
var theKeyValue = array[x].substring(0, equal);
var userDataValue = array[x];
userDataValue = decodeURIComponent(userDataValue); //Puts symbols back
userData[theKeyValue] = userDataValue;
}
This is just an example to follow up with the usage of associative arrays, hopefully this helps. :)
See Wikipedia.
It is a data structure when you can look up a value by a key. This is typically implemented in JS using a Map or an Object.
const data = new Map([
['foo', 'one'],
['bar', 'two']
]);
console.log( data.get("bar") );
I expected for it to target the index in which the string "one" is in, but an error occurs.
You are attempting to look up the index of a property in an array by its value.
That has nothing to do with associative arrays and is achieved with the indexOf method.
var array = ["one", "two", "three"];
var test = array.indexOf("one");
console.log(test);
An associative array, is essentially a hashmap, or an array that associates relationships.
For example if I was to build an associative array for fruits let's say to prices it would look like.
const arr = {'apple': 1, 'orange': 2, 'pear': 3};
console.log(Object.keys(arr));
console.log(Object.values(arr));
Unlike other languages, array in Javascript are not limited by having only numeric indices. They can act as hashes as well (i.e. having a string as a key). An associative array is one where you set the key to be a non-numeric value.
By default, and in the example you provided, ascending numeric values are assigned to each member of the array. I.e.
var array = ["one", "two", "three"];
is equivalent to
var array = [];
array[0] = 'one';
array[1] = 'two';
array[2] = 'three';
An associative array would be one where instead of numeric values you assign a different value:
var array = [];
array['one'] = 'one';
array['two'] = 'two';
However this brings a few caveats in itself and it considered bad practice and the arrays become harder to manage. In cases like there it would be better to use either an object or a Map.
An associative array is a data structure, a data collection, which has the scope of associate a list of key to respective values (key: value).
You can read in Wikipedia here, that are example of associative array for example: Map, Dictionary, etc.
Sample of associative array are also PHP indexed array, e.g.:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
That's not an associative array, that's just a regular array, filled with text.
An associative array example (you can also use object syntax like Miroslav's answer):
var stuff = [];
stuff['one'] = "hello 1";
stuff['two'] = "hello 2";

Javascript: Subarrays contain reference to other arrays even though parent is its own array? [duplicate]

This question already has answers here:
How do you clone an array of objects in JavaScript?
(40 answers)
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 4 years ago.
OK.
Let me try to say this in some sort of comprehensible manner. I'm an amateur programmer writing my own take on a neural network in javascript. (Without having seen the code for a neural network before)
I was having problems with an array changing when I was trying to change a copy of the array. (Not the original)
I soon realized after rereading what I'd written that when you assign an identifier to an array it doesn't make the identifier a new object with a copy of the array. Instead, it makes a reference to the original array object, for example:
var arr = [1,2,3];
var arr2 = arr;
arr2[0] = 9;
alert(arr);
//Alerts "9,2,3"
With this mind, I googled and found a quick solution:
var arr = [1,2,3];
var arr2 = arr.slice();
arr2[0] = 9;
alert(arr);
//Alerts "1,2,3"
So I changed this in my actual project expecting to see my work completed, but no! I was getting the exact results as before where my array was changing even though it was not supposed to.
After much effort at debugging, I finally worked out that the problem here is that I have a large array of subarrays, which in turn have subarrays.
In code this looks like:
var arr = [
[[1],[2]],
[[4],[5]],
[[7],[8]]
];
As you can see, there is one big array that contains 3 smaller arrays, each of which contains two even smaller arrays, each of which contains a number.
In my project, it's more complicated than this and has a couple more layers but this is a decent representation.
So what did I expect to happen?
var arr = [
[[1],[2]],
[[4],[5]],
[[7],[8]]
];
var other = arr.slice();
other[0][0][0] = "Uh Oh";
alert(arr);
//Outputs "1,2,3,4,5,6,7,8"
What actually happened?
alert(arr);
//Outputs "Uh Oh,2,3,4,5,6,7,8"
Why does this happen?
How can I fix it?
Thanks in advance.
Try following
var arr = [
[[1],[2]],
[[4],[5]],
[[7],[8]]
];
var other = JSON.parse(JSON.stringify(arr));
other[0][0][0] = "Uh Oh";
console.log(arr);
Reasoning
arr.slice() creates different reference for the array, however, any child object/array will still continue to hold the same reference. But you need to change the references of the child object/array as well, for that convert it into a string and then back to object - It will create different references for all the objects.

javascript difference between var myArray = new Array( ... ) and var myArray = ["one","two", 3]? [duplicate]

What's the real difference between declaring an array like this:
var myArray = new Array();
and
var myArray = [];
There is a difference, but there is no difference in that example.
Using the more verbose method: new Array() does have one extra option in the parameters: if you pass a number to the constructor, you will get an array of that length:
x = new Array(5);
alert(x.length); // 5
To illustrate the different ways to create an array:
var a = [], // these are the same
b = new Array(), // a and b are arrays with length 0
c = ['foo', 'bar'], // these are the same
d = new Array('foo', 'bar'), // c and d are arrays with 2 strings
// these are different:
e = [3] // e.length == 1, e[0] == 3
f = new Array(3), // f.length == 3, f[0] == undefined
;
Another difference is that when using new Array() you're able to set the size of the array, which affects the stack size. This can be useful if you're getting stack overflows (Performance of Array.push vs Array.unshift) which is what happens when the size of the array exceeds the size of the stack, and it has to be re-created. So there can actually, depending on the use case, be a performance increase when using new Array() because you can prevent the overflow from happening.
As pointed out in this answer, new Array(5) will not actually add five undefined items to the array. It simply adds space for five items. Be aware that using Array this way makes it difficult to rely on array.length for calculations.
The difference between creating an array with the implicit array and the array constructor is subtle but important.
When you create an array using
var a = [];
You're telling the interpreter to create a new runtime array. No extra processing necessary at all. Done.
If you use:
var a = new Array();
You're telling the interpreter, I want to call the constructor "Array" and generate an object. It then looks up through your execution context to find the constructor to call, and calls it, creating your array.
You may think "Well, this doesn't matter at all. They're the same!". Unfortunately you can't guarantee that.
Take the following example:
function Array() {
this.is = 'SPARTA';
}
var a = new Array();
var b = [];
alert(a.is); // => 'SPARTA'
alert(b.is); // => undefined
a.push('Woa'); // => TypeError: a.push is not a function
b.push('Woa'); // => 1 (OK)
In the above example, the first call will alert 'SPARTA' as you'd expect. The second will not. You will end up seeing undefined. You'll also note that b contains all of the native Array object functions such as push, where the other does not.
While you may expect this to happen, it just illustrates the fact that [] is not the same as new Array().
It's probably best to just use [] if you know you just want an array. I also do not suggest going around and redefining Array...
There is an important difference that no answer has mentioned yet.
From this:
new Array(2).length // 2
new Array(2)[0] === undefined // true
new Array(2)[1] === undefined // true
You might think the new Array(2) is equivalent to [undefined, undefined], but it's NOT!
Let's try with map():
[undefined, undefined].map(e => 1) // [1, 1]
new Array(2).map(e => 1) // "(2) [undefined × 2]" in Chrome
See? The semantics are totally different! So why is that?
According to ES6 Spec 22.1.1.2, the job of Array(len) is just creating a new array whose property length is set to the argument len and that's it, meaning there isn't any real element inside this newly created array.
Function map(), according to spec 22.1.3.15 would firstly check HasProperty then call the callback, but it turns out that:
new Array(2).hasOwnProperty(0) // false
[undefined, undefined].hasOwnProperty(0) // true
And that's why you can not expect any iterating functions working as usual on arrays created from new Array(len).
BTW, Safari and Firefox have a much better "printing" to this situation:
// Safari
new Array(2) // [](2)
new Array(2).map(e => 1) // [](2)
[undefined, undefined] // [undefined, undefined] (2)
// Firefox
new Array(2) // Array [ <2 empty slots> ]
new Array(2).map(e => 1) // Array [ <2 empty slots> ]
[undefined, undefined] // Array [ undefined, undefined ]
I have already submitted an issue to Chromium and ask them to fix this confusing printing:
https://bugs.chromium.org/p/chromium/issues/detail?id=732021
UPDATE: It's already fixed. Chrome now printed as:
new Array(2) // (2) [empty × 2]
Oddly enough, new Array(size) is almost 2x faster than [] in Chrome, and about the same in FF and IE (measured by creating and filling an array). It only matters if you know the approximate size of the array. If you add more items than the length you've given, the performance boost is lost.
More accurately: Array( is a fast constant time operation that allocates no memory, wheras [] is a linear time operation that sets type and value.
For more information, the following page describes why you never need to use new Array()
You never need to use new Object() in
JavaScript. Use the object literal {}
instead. Similarly, don’t use new Array(),
use the array literal []
instead. Arrays in JavaScript work
nothing like the arrays in Java, and
use of the Java-like syntax will
confuse you.
Do not use new Number, new String, or
new Boolean. These forms produce
unnecessary object wrappers. Just use
simple literals instead.
Also check out the comments - the new Array(length) form does not serve any useful purpose (at least in today's implementations of JavaScript).
In order to better understand [] and new Array():
> []
[]
> new Array()
[]
> [] == []
false
> [] === []
false
> new Array() == new Array()
false
> new Array() === new Array()
false
> typeof ([])
"object"
> typeof (new Array())
"object"
> [] === new Array()
false
> [] == new Array()
false
The above result is from Google Chrome console on Windows 7.
The first one is the default object constructor call. You can use it's parameters if you want.
var array = new Array(5); //initialize with default length 5
The second one gives you the ability to create not empty array:
var array = [1, 2, 3]; // this array will contain numbers 1, 2, 3.
I can explain in a more specific way starting with this example that's based on Fredrik's good one.
var test1 = [];
test1.push("value");
test1.push("value2");
var test2 = new Array();
test2.push("value");
test2.push("value2");
alert(test1);
alert(test2);
alert(test1 == test2);
alert(test1.value == test2.value);
I just added another value to the arrays, and made four alerts:
The first and second are to give us the value stored in each array, to be sure about the values. They will return the same!
Now try the third one, it returns false, that's because
JS treats test1 as a VARIABLE with a data type of array, and it treats test2 as an OBJECT with the functionality of an array, and
there are few slight differences here.
The first difference is when we call test1 it calls a variable without thinking, it just returns the values that are stored in this variable disregarding its data type!
But, when we call test2 it calls the Array() function and then it stores our "Pushed" values in its "Value" property, and the same happens when we alert test2, it returns the "Value" property of the array object.
So when we check if test1 equals test2 of course they will never return true, one is a function and the other is a variable (with a type of array), even if they have the same value!
To be sure about that, try the 4th alert, with the .value added to it; it will return true. In this case we tell JS "Disregarding the type of the container, whether was it function or variable, please compare the values that are stored in each container and tell us what you've seen!" that's exactly what happens.
I hope I said the idea behind that clearly, and sorry for my bad English.
There is no difference when you initialise array without any length. So var a = [] & var b = new Array() is same.
But if you initialise array with length like var b = new Array(1);, it will set array object's length to 1. So its equivalent to var b = []; b.length=1;.
This will be problematic whenever you do array_object.push, it add item after last element & increase length.
var b = new Array(1);
b.push("hello world");
console.log(b.length); // print 2
vs
var v = [];
a.push("hello world");
console.log(b.length); // print 1
There's more to this than meets the eye. Most other answers are correct BUT ALSO..
new Array(n)
Allows engine to reallocates space for n elements
Optimized for array creation
Created array is marked sparse which has the least performant array operations, that's because each index access has to check bounds, see if value exists and walk the prototype chain
If array is marked as sparse, there's no way back (at least in V8), it'll always be slower during its lifetime, even if you fill it up with content (packed array) 1ms or 2 hours later, doesn't matter
[1, 2, 3] || []
Created array is marked packed (unless you use delete or [1,,3] syntax)
Optimized for array operations (for .., forEach, map, etc)
Engine needs to reallocate space as the array grows
This probably isn't the case for older browser versions/browsers.
The first one is the default object constructor call.mostly used for dynamic values.
var array = new Array(length); //initialize with default length
the second array is used when creating static values
var array = [red, green, blue, yellow, white]; // this array will contain values.
The difference of using
var arr = new Array(size);
Or
arr = [];
arr.length = size;
As been discussed enough in this question.
I would like to add the speed issue - the current fastest way, on google chrome is the second one.
But pay attention, these things tend to change a lot with updates. Also the run time will differ between different browsers.
For example - the 2nd option that i mentioned, runs at 2 million [ops/second] on chrome, but if you'd try it on mozilla dev. you'd get a surprisingly higher rate of 23 million.
Anyway, I'd suggest you check it out, every once in a while, on different browsers (and machines), using site as such
As I know the diference u can find the slice(or the other funcitons of Array) like code1.and code2 show u Array and his instances:
code1:
[].slice; // find slice here
var arr = new Array();
arr.slice // find slice here
Array.prototype.slice // find slice here
code2:
[].__proto__ == Array.prototype; // true
var arr = new Array();
arr.__proto__ == Array.prototype; // true
conclusion:
as u can see [] and new Array() create a new instance of Array.And they all get the prototype functions from Array.prototype
They are just different instance of Array.so this explain why
[] != []
:)
There is no big difference, they basically do the same thing but doing them in different ways, but read on, look at this statement at W3C:
var cars = ["Saab", "Volvo","BMW"];
and
var cars = new Array("Saab", "Volvo", "BMW");
The two examples above do exactly the same. There is no need to use
new Array(). For simplicity, readability and execution speed, use the
first one (the array literal method).
But at the same time, creating new array using new Array syntax considered as a bad practice:
Avoid new Array()
There is no need to use the JavaScript's built-in array constructor
new Array().
Use [] instead.
These two different statements both create a new empty array named
points:
var points = new Array(); // Bad
var points = []; // Good
These two different statements both create a new array containing 6
numbers:
var points = new Array(40, 100, 1, 5, 25, 10); // Bad
var points = [40, 100, 1, 5, 25, 10]; // Good
The new keyword only complicates the code. It can also produce some
unexpected results:
var points = new Array(40, 100); // Creates an array with two elements (40 and 100)
What if I remove one of the elements?
var points = new Array(40); // Creates an array with 40 undefined elements !!!!!
So basically not considered as the best practice, also there is one minor difference there, you can pass length to new Array(length) like this, which also not a recommended way.
I've incurred in a weird behaviour using [].
We have Model "classes" with fields initialised to some value. E.g.:
require([
"dojo/_base/declare",
"dijit/_WidgetBase",
], function(declare, parser, ready, _WidgetBase){
declare("MyWidget", [_WidgetBase], {
field1: [],
field2: "",
function1: function(),
function2: function()
});
});
I found that when the fields are initialised with [] then it would be shared by all Model objects. Making changes to one affects all others.
This doesn't happen initialising them with new Array(). Same for the initialisation of Objects ({} vs new Object())
TBH I am not sure if its a problem with the framework we were using (Dojo)
Well, var x = new Array() is different than var x = [] is different in some features I'll just explain the most useful two (in my opinion) of them.
Before I get into expalining the differences, I will set a base first; when we use x = [] defines a new variable with data type of Array, and it inherits all the methods that belong to the array prototype, something pretty similar (but not exactly) to extending a class. However, when we use x = new Array() it initilizes a clone of the array prototype assigned to the variable x.
Now let's see what are the difference
The First Difference is that using new Array(x) where x is an integer, initilizes an array of x undefined values, for example new Array(16) will initialize an array with 16 items all of them are undefined. This is very useful when you asynchronously fill an array of a predefined length.
For example (again :) ) let's say you are getting the results of 100 competitiors, and you're receiving them asynchronously from a remote system or db, then you'll need to allocate them in the array according to the rank once you receive each result. In this very rare case you will do something like myArray[result.rank - 1] = result.name, so the rank 1 will be set to the index 0 and so on.
The second difference is that using new Array() as you already know, instanciates a whole new clone of the array prototype and assigns it to your variable, that allows you to do some magic (not recommended btw). This magic is that you can overwrite a specific method of the legacy array methods. So, for example you can set the Array.push method to push the new value to the beginning of the array instead of the end, and you can also add new methods (this is better) to this specific clone of the Array Prototype. That will allow you to define more complex types of arrays throughout your project with your own added methods and use it as a class.
Last thing, if you're from the very few people (that I truly love) that care about processing overhead and memory consumption of your app, you'd never tough new Array() without being desperate to use it :).
I hope that has explained enough about the beast new Array() :)
I found a difference while using promises. While using array of promises (say arr, initialised as arr=[]), got an error in Promise.all(arr). Whereas when declared as arr = Array(), did not get compilation issues. Hope this helps.
I've found one difference between the two constructions that bit me pretty hard.
Let's say I have:
function MyClass(){
this.property1=[];
this.property2=new Array();
};
var MyObject1=new MyClass();
var MyObject2=new MyClass();
In real life, if I do this:
MyObject1.property1.push('a');
MyObject1.property2.push('b');
MyObject2.property1.push('c');
MyObject2.property2.push('d');
What I end up with is this:
MyObject1.property1=['a','c']
MyObject1.property2=['b']
MyObject2.property1=['a','c']
MyObject2.property2=['d']
I don't know what the language specification says is supposed to happen, but if I want my two objects to have unique property arrays in my objects, I have to use new Array().
Using the Array constructor makes a new array of the desired length and populates each of the indices with undefined, the assigned an array to a variable one creates the indices that you give it info for.

Test for value within array of objects

I am dynamically building an array of objects using a process that boils down to something like this:
//Objects Array
var objects = [];
//Object Structure
var object1 = {"id":"foobar_1", "metrics":90};
var object2 = {"id":"some other foobar", "metrics":50};
objects[0] = object1;
objects[1] = object2;
(Let it be said for the record, that if you can think of a better way to dynamically nest data such that I can access it with objects[i].id I am also all ears!)
There's ultimately going to be more logic at play than what's above, but it's just not written yet. Suffice it to say that the "object1" and "object2" parts will actually be in an iterator.
Inside that iterator, I want to check for the presence of an ID before adding another object to the array. If, for example, I already have an object with the ID "foobar_1", instead of pushing a new member to the array, I simply want to increment its "metrics" value.
If I wasn't dealing with an array of objects, I could use inArray to look for "foobar_1" (a jQuery utility). But that won't look into the object's values. The way I see it, I have two options:
Keep a separate simple array of just the IDs. So instead of only relying on the objects array, I simply check inArray (or plain JS equivalent) for a simple "objectIDs" array that is used only for this purpose.
Iterate through my existing data object and compare my "foobar_1" needle to each objects[i].id haystack
I feel that #1 is certainly more efficient, but I can't help wondering if I'm missing a function that would do the job for me. A #3, 4, or 5 option that I've missed! CPU consumption is somewhat important, but I'm also interested in functions that make the code less verbose whether they're more cycle-efficient or not.
I'd suggest switching to an object instead of an array:
var objects = {};
objects["foobar_1"] = {metrics: 90};
objects["some other foobar"] = {metrics: 50};
Then, to add a new object uniquely, you would do this:
function addObject(id, metricsNum) {
if (!(id in objects)) {
objects[id] = {metrics: metricsNum};
}
}
To iterate all the objects, you would do this:
for (var id in objects) {
// process objects[id]
}
This gives you very efficient lookup for whether a given id is already in your list or not. The only thing it doesn't give you that the array gave you before is a specific order of objects because the keys of an object don't have any specific order.
Hmm , i wonder why dont you use dictionary cause that is perfectlly fits your case. so your code will be as below:
//Objects Array
var objects = [];
//Object Structure
var object1 = {"metrics":90};
var object2 = {"metrics":50};
objects["foobar_1"] = object1;
objects["some other foobar"] = object2;
// An example to showing the object existence.
if (!objects["new id"]){
objects["new id"] = {"metrics": 100};
}
else {
objects["new id"].matrics++;
}

Categories

Resources