How to find index of object in array without iterating in javascript - javascript

Lets have an sample array like [1,2,3,4,5,6,7,8,9,10,12,0, 1, 2, 3,4 ]
I want to find the first occurrence of ' 0 ' in this array, but without iterating the same.
all the functions 'like', 'map', 'grep', 'filter', 'some','for each' everything iterating every element in the array to find the same. Considering big data array's its very much bottleneck considering performance.
I have tried all the above methods.
Anybody has any idea about this?. Thanks for your time.

How to find index of object in array without iterating in javascript
This is impossible. If you have a generic list of values, you have to look at each element until you find the one you are looking for.
If you want O(1) access then you need to use a different data structure.

If the elements of the array is a number or string, you can just use indexOf()
indexOf() compares searchElement (first parameter) to elements of the Array using strict
equality (the same method used by the ===, or triple-equals,
operator).
var list = [1,2,3,4,5,6,7,8,9,10,12,0, 1, 2, 3,4 ];
var firstOccurence = list.indexOf(0);

Related

What exactly is a dense array?

The explanation for a dense array that I read from a few pages seem to be in contradiction to one another. I'd like some help understanding what it is.
While some links (search result 1, search result 2) suggest that it simply is an array where:
the elements of the array are known to be specific values; and
are assigned to the array at the time of its initialization.
The allusion there is that JavaScript arrays are dense.
It all makes sense up until here.
But this statement taken from the JavaScript Guide on the Mozilla Developer Network (MDN) says:
Since an array's length can change at any time, and data can be stored at non-contiguous locations in the array, JavaScript arrays are
not guaranteed to be dense; this depends on how the programmer chooses
to use them. In general, these are convenient characteristics; but if
these features are not desirable for your particular use, you might
consider using typed arrays.
And this has confused me now. My question is:
What does the statement on the MDN page mean when it says JavaScript arrays are not guaranteed to be dense? If it means that the following is not a dense array because one or more of its elements are undefined at the time of initialization, then why do the links I listed above seem to indicate that JavaScript arrays are indeed dense?
var array = new Array(1, , 3, ); // [1, undefined, 3, undefined]
"Dense" is in opposition to "sparse", and generally is used when talking about storage. For example, this array is dense:
a = [undefined, undefined, 2]
It can be stored in memory exactly like that: a sequence of three locations, the first two being undefined, the third being 2.
This array is sparse:
a = []
a[100000000] = 100000000
It is not stored in memory as a sequence of 100000001 locations, as it would be horribly inefficient. It is definitely not 100000000 places of undefined followed by 100000000. Rather, it just says 100000000th one is 100000000, and there is no space allocated to the first 100000000 elements.
(Actually, try to do this with 2 instead of 100000000, and you'll notice a curious thing: Chrome will display the dense array as [undefined, undefined, 2], but the sparse one as [undefined × 2, 2].)
Those articles say you can create an array being dense. This means that, at the time of creation, such arrays are dense, since in arrays like:
var a = new Array("foo", "bar", "baz");
var b = [2, 3, 5];
every element is set: from 0 to length-1, there is no undefined value. Or better said: every position from 0 to length-1 was assigned a value (even if the value is, actually, undefined).
However, you can make those arrays not dense anymore, by doing something like this:
a[20] = "bat";
That array, which was dense, is not dense anymore since the elements 0 1 2 and 20 (unlike elements in 3 to 19) are set to a value (this array has 4 elements, not 21).

Why is deleting from an object faster than splicing array?

I was curious to see the speed differences between arrays and objects, so I set up a test for filling, accessing, and deleting 100,000 items from an array and object. Accessing and filling the array were about equal with a ~3ms difference. Deleting from the array, however, resulted in 604ms difference(10ms vs 614ms). Why is this? I thought objects and arrays were pretty much the same.
Demo: https://codecanister.com/Project/b9f8de7c/1/result/
When you do that .splice(), all the subsequent array entries have to be reassigned. That is, every property name after the one spliced out must be changed. There's no good way to do that except a straight linear traversal of the properties; a data structure that made that operation fast would make other, more common operations slower.
So consider the array [1, 2, 3, 4]. The value of property "0" is 1. If you splice that entry out, then the runtime has to set property "0" to 2, property "1" to 3, and property "2" to 4.
You just perform different actions. "delete" will just set the array-position to undefined. While splice will totally remove it by performing a loop with arr[i] = arr[i+1] for all 10,000 items of your array. You do this for all 10.000 items. See also this question

Create an associative array with integer keys

I need to create an associative array in javascript with an integer key as follows;
a["10"] = "ten";
but when i create an array, it puts the value to the 10th index of the array and it creates an array with the length 11. I want it to be a key value pair. I know this can be done by using objects but i need an array only.
JavaScript does not have associative arrays. The only way to do this in JavaScript is to use objects:
var a = {
'10': 'ten'
};
ECMAScript does have Associated Arrays1 - Objects (and by extension, Arrays) are an example
However, some properties of Arrays are treated specially:
Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P ..
.. Specifically, whenever a property is added whose name is an array index, the length property is changed, if necessary, to be one more than the numeric value of that array index ..
Thus, given arr = [], the expressions arr["1"] and arr[1] refer to the same property name. Since P (the property name) is "1" and length is 0 from above, then assignment to such property will set arr.length to ToUint32(P)+1, or 2.
It is not possible to change this behavior. If you wish to not have a special length property, then use a "normal" Object instead of an Array. However, many of the Array.prototype functions can be used with arbitrary objects (with some implementation quirks aside) that have a length property and an Object can be created such that it uses Array.prototype as its own prototype.
All that being said, the post does not say what the real issue is. Instead of supposing that it must be done in that particular manner, consider explaining what the intent is: e.g. why a["10"]? And what is wrong if there are "11 items" if the object will be used in a List?
1 Please read the article before debating this statement: the term "Array" in the name does not imply an ordered sequence nor does it preclude an additional notion of a Length or the use of Hashing, etc. If you are going by a different definition, make sure to specify what it is and what the desired behavior is for a given operation.

Returning number of elements of JSON object

I need to iterate over every element in a JSON object, and I'm having trouble working out a way to count the number of elements in that object so I can use a for loop to iterate. Here's my object:
this.worldData =[
{"0":{"1":"0", "2":"0"},
"1":{"1":"0", "2":"0"},
"2":{"1":"0", "2":"0"}}
];
And what I'm trying:
alert(this.worldData.length);
Problem is, it always returns 1, no matter how many elements I put into the JSON object.
Do you have control over the JSON data? The length is returning 1 because there is only one element in the array. This is because of the way the JSON data is structured here. If you want something easier to iterate over, you would want something like this:
this.worldData = [
{"1":"0","2":"0"},
{"1":"0","2":"0"},
{"1":"0","2":"0"}
]
Note that objects (denoted with {}) don't have a length property, while arrays (denoted with []) do.
You're wrapping all of your objects inside a single object (the first and last curly braces). Try this:
this.worldData =[
{"0":{"1":"0", "2":"0"}},
{"1":{"1":"0", "2":"0"}},
{"2":{"1":"0", "2":"0"}}
];
jsFiddle example.

How do I access the first key of an ‘associative’ array in JavaScript?

I have a js 'associative' array, with
array['serial_number'] = 'value'
serial_number and value are strings.
e.g. array['20910930923'] = '20101102'
I sorted it by value, works fine.
Let's say I get back the object 'sorted';
Now I want to access the first KEY of the 'sorted' array.
How do I do it? I can't think I need an iteration with
for (var i in sorted)
and just stop after ther first one...
thanks
edit: just to clarify, I know that js does not support associative arrays (that's why I put it in high commas in the Title).
2021 Update
Since ES6, properties with string keys are enumerated in insertion order. Here's a nice summary. My original answer from 2010 was correct at the time and is preserved below:
Original answer
JavaScript object properties are specified to have no order, much though many people wish it were different. If you need ordering, abandon any attempt to use an object and use an Array instead, either to store name-value objects:
var nameValues = [
{name: '20910930923', value: '20101102'},
{name: 'foo', value: 'bar'}
];
... or as an ordered list of property names to use with your existing object:
var obj = {
'20910930923': '20101102',
'foo': 'bar'
};
var orderedPropertyNames = ['20910930923', 'foo'];
Try this:
// Some assoc list
var offers = {'x':{..some object...}, 'jjj':{...some other object ...}};
// First element (see attribution below)
return offers[Object.keys(offers)[0]];
// Last element (thanks to discussion on finding last element in associative array :)
return offers[Object.keys(offers)[Object.keys(offers).length - 1]];
Actually JavaScript doesn't support associative arrays, so you can't loop through it in an implied order (e.g. you can't access it via the indexer property array[0] won't access the first element in your object). The syntax is what makes it look like it does, but in reality it doesn't. So you have no "Order" to your objects.
http://www.hunlock.com/blogs/Mastering_Javascript_Arrays
Javascript does not have, and does not
support Associative Arrays. However…
All arrays in Javascript are objects
and Javascript's object syntax gives a
basic emulation of an associative
Array. For this reason the example
code above will actually work. Be
warned that this is not a real array
and it has real pitfals if you try to
use it. The 'person' element in the
example becomes part of the Array
object's properties and methods, just
like .length, .sort(), .splice(), and
all the other built-in properties and
methods.
Just thinking off the top of my head, but could you have another array with the key value pairs swapped?
So the answer would be arrayKeyValueReversed['20101102'] = '20910930923';
When you sort the array, use the first item (array[0]) as the key to get the value in the arrayKeyValueReversed.

Categories