Array length is not correct in javascript - javascript

I have an array like below
arr=[];
arr[0]={"zero": "apple"};
arr[1]={"one": "orange"};
arr["fancy"]="what?";
but i am getting length as 2 when i do console.log(arr.length) even though i am able to console all the values .
and not able to get all values while doing console.log(JSON.stringify(arr))
What is the issue here.
here is the link to fiddle fiddle

.length is a special property in Javascript arrays, which is defined as "the biggest numeric index in the array plus one" (or 2^32-1, whatever comes first). It's not "the number of elements", as the name might suggest.
When you iterate an array, either directly with for..of or map, or indirectly with e.g. JSON.stringify, JS just loops over all numbers from 0 to length - 1, and, if there's a property under this number, outputs/returns it. It doesn't look into other properties.

The length property don't work as one will expect on arrays that are hashtables or associative arrays. This property only works as one will expect on numeric indexed arrays (and normalized, i.e, without holes). But there exists a way for get the length of an associative array, first you have to get the list of keys from the associative array using Object.keys(arr) and then you can use the length property over this list (that is a normalized indexed array). Like on the next example:
arr=[];
arr[0]={"zero": "apple"};
arr[1]={"one": "orange"};
arr["fancy"]="what?";
console.log(Object.keys(arr).length);
And about this next question:
not able to get all values while doing console.log(JSON.stringify(arr))
Your arr element don't have the correct format to be a JSON. If you want it to be a JSON check the syntax on the next example:
jsonObj = {};
jsonObj[0] = {"zero": "apple"};
jsonObj[1] = {"one": "orange"};
jsonObj["fancy"] = "what?";
console.log(Object.keys(jsonObj).length);
console.log(JSON.stringify(jsonObj));

From MDN description on arrays, here, "Arrays cannot use strings as element indexes (as in an associative array) but must use integers."
In other words, this is not Javascript array syntax
arr["fancy"]="what?";
Which leads to the error in .length.

Related

Why 'delete' replaces value with undefined in arrays but in objects it is able to remove the property completely?

What differences in object and arrays cause this? Why is Object able to remove the element and array cannot? Does Object automatically makes a check to not display undefined values?
delete will remove properties entirely from arrays.
const array = [0,1,2];
delete array[1];
console.log("0" in array);
console.log("1" in array);
Since most tools that display an array for debugging purposes will not display them with explicit index values, any missing values will typically be rendered as undefined.
If they didn't then you wouldn't be able to tell the difference between these two examples:
const sparse = [1,,2];
const full = [1,2];
console.log(sparse);
console.log(full);
If you want to shuffle the indexes of every subsequent item down the array, then you need to look at the splice method.

In javascript how to replace elements of an array to it's corresponding values in another object?

I have the mapping of abbreviation and full name as follow:
object = {"TSLA":"TESLA INC.","GOOG":"GOOGLE INC.","APPL":"APPLE INC.","AMZN":"AMAZON CORPORATION", "MSFT":"MICROSOFT CORPORATION"}
as an output of function i get the following array:
array = ["AMZN","APPL"]
I want to display the values of the associated keys as follows:
output_array = ["AMAZON CORPORATION", "APPLE INC."]
Note that, the actual object has more key: value pairs
Using IndexOf() I can replace one value. However, I believe there must be a way of mapping the array elements to replace the values at once.
Since I am new to JS, I would appreciate any suggestion.
array.map(abbr => object[abbr]) does the job; it iterates over the array rather than the object, which is more efficient as the object already is a lookup table with the right keys - you are right, there is no need to use indexOf which uses a linear search.

Javascript slice isn't giving me correct array length values

Why does it say length 1 instead of 4?
The following is what I'm trying to push and slice. I try and append items.image_urls and slice them into 5 each.
items.image_urls is my dictionary array.
var final_push = []
final_push.push(items.image_urls.splice(0,5))
console.log(final_push.length)## gives me 1...?
var index = 0
final_push.forEach(function(results){
index++ ##this gives me one. I would need 1,2,3,4,5,1,2,3,4,5. Somehting along that.
}
items.image_urls looks like this:
It's an iteration of arrays with image urls.
In your example items.image_urls.splice(0,5) returns an array of items removed from items.image_urls. When you call final_push.push(items.image_urls.splice(0,5));, this whole array is pushed as one item to the final_push array, so it now looks like [["url1", "url2", "url3", "url4", "url5"]] (2-dimensional array). You can access this whole array by calling final_push[some_index].
But what you want instead is to add every element of items.image_urls.splice(0,5) to the final_push. You can use a spread operator to achieve this:
final_push.push(...items.image_urls.splice(0,5));
Spread syntax allows an iterable such as an array expression or string
to be expanded in places where zero or more arguments (for function
calls) or elements (for array literals) are expected
This is exactly our case, because push() expects one or more arguments:
arr.push(element1[, ...[, elementN]])
And here is an example:
let items = {
image_urls: ["url1", "url2", "url3", "url4", "url5", "url6", "url7", "url8", "url9", "url10"]
};
let final_push = [];
final_push.push(...items.image_urls.splice(0,5));
console.log(final_push.length);
console.log(JSON.stringify(final_push));
console.log(JSON.stringify(items.image_urls));
Note: do not confuse Array.prototype.slice() with Array.prototype.splice() - the first one returns a shallow copy of a portion of an array into a new array object while the second changes the contents of an array by removing existing elements and/or adding new elements and returns an array containing the deleted elements.
That seems to be a nested array. So if you would access index 0, and then work on that array like below it will probably work:
console.log(final_push[0].length); //should print 4
The author is mixing up splice and slice. Probably a typo :)
You start at the beginning (0) and then delete 5 items.

Length of Array within Array

I have an object that I am pushing some ints, strings and arrays into an array. And I want to get the length of the array that is within said array.
This is my code
var all_categories = [];
all_categories.push({
title: theTitle,
id: theId,
sub: subcategories
});
Now I know that all_categories.length is the general way of getting the length and I believe that I can't run all_categories[0].sub[0].length will not work because the function does not exist.
Suggestions for a solution or work around?
In your statement all_categories[0].sub[0].length refers to the length of the first element of array named sub.
In order to see length of the array you should call:
all_categories[0].sub.length
Assuming that subcategories is the array you want the length of, take out the second [0]. You aren't trying to get the length of the first subcategory, you're trying to get the number of subcategories.

JavaScript Array Length Key Value

Why is this extremely basic JavaScript array giving me a length of 13 when there are only 3 key/value pairs in it. It makes sense that it might think 13 as 0 based index and my last array has a key of 12, but I need to have any array that has a key/value pair that returns me the correct number of pairs. The keys need to be numbers.
http://jsfiddle.net/fmgc8/1/
EDIT: this is how I solved it thanks.
http://jsfiddle.net/fmgc8/4/
it's because the highest number you have is:
array['12'] = 'twelve';
This creates an array length of 13 (since it's 0 based). JavaScript will expand the array to allocate the number of spots it needs to satisfy your specified slots. array[0..9] is there, you just haven't placed anything in them.
There is no diffrence between array['12'] and array[12] (array['12'] is not considered as associative array element). To find associative array length
The length property of arrays returns the biggest non-negative numeric key of the object, plus one. That's just the way it's defined.
If you want to count the key-value pairs, you're going to have to count them yourself (either by keeping track of them as they are added and removed, or by iterating through them).
Or, rearrange your array like this:
var array = [];
array.push(['10','ten']);
array.push(['11','eleven']);
array.push(['12','twelfe']);
alert(array.length);

Categories

Resources