Inserting items into array with bracket syntax doesnt affect length? - javascript

An array's length does not increase when adding items with bracket syntax. How do you update the length?
Example:
const a = [];
a['u123'] = 1;
a['u456'] = 2;
a.length; // returns 0

Arrays do not have keys, so your way of accessing them is also wrong. You could instead use push to add values to the array and the values will be index based, not key based.
const a = [];
a.push('u123');
a.push('u456');
console.log(a.length);
Or you could make your data an object instead, to have a key-value pair:
const a = {};
a['u123'] = 1;
a['u456'] = 2;
console.log(Object.keys(a).length)

That's because you are not adding items to the array instead you are inserting entries (key-value pairs) to your object.
You can check the length of the entries using the below syntax:
Object.keys(a).length // returns 2
If you want to add items to the array, use the below syntax:
a.push(1);
a.push('u123')
// ES6 syntax using spread operator
a = [...a, 2, 'u456']
a.length // returns 4

In order to get the length of an associative array you need to use the Object.keys length
Like so:
console.log(Object.keys(a).length);

If you want to update the length you need to use push. If you are using brackets you are adding a new property to an object (remember that an array is an object).
The length property return the number of elements in the array (not the properties).
var arrA = new Array();
var arrB = new Array();
arrA['propertyOne'] = 1; //add property 'propertyOne' with value 1 to the object arrA
arrA.push(2);
arrB.push(1);
arrB.push(2);
console.log(arrA); // [2, propertyOne: 1]
console.log(arrA[0]); // 2
console.log(arrA['propertyOne']); // 1
console.log(arrA.hasOwnProperty('propertyOne')); // true
console.log(arrA.length); // 1
console.log(arrB); // [1, 2]
console.log(arrB.length); // 2

Related

Possible to push empty slot to an array?

I'm building my own map method to be as close as the native map method.
Since the native map pushes(i think) the changed values into a new array, it still keeps the empty slots. I wasn't able to find a solution to push an empty slot into an array, like this example below.
[1, 2, 3].push(some code) // [1, 2, 3, empty]
I tried pushing an array with one empty item prefixed with a spread operator arr.push(...(new Array(1))) or arr.push(...[,]) but that just pushes undefined.
I solved my problem by not using push and instead assigning values to the array index that way skipped indices will be set to empty.
But I'm writing this post to see if anyone knows that if it's possible to use the push method to push an empty slot to an array.
No, it's not possible, not with the push method. empty can only exist if the array has a certain length, but a whole number property of the array does not exist at some index. This is called a sparse array, and cannot be created with push (or other array methods, if they're called on and with non-sparse arrays).
The only way to do so would be to assign to an index for which a lower index doesn't exist yet.
Look at the results for the below two snippets in your browser console, not the snippet console:
const arr = [];
arr[1] = 'a';
console.log(arr);
Or to set the .length of the array above the last index that the array has:
const arr = [];
arr.length = 1;
console.log(arr);
But the two approaches above are very weird to do and probably have no good reason to be used. Better to avoid sparse arrays entirely.
Keep in mind that an empty slot is different from undefined, which is perfectly possible to have as an array value:
const arr = [];
arr.push(undefined);
console.log(arr);
You can create an empty slot in an array by incrementing the array length:
var a = []
a.push(1)
a.length++
a.push(3)
console.log(a)
console.log(1 in a) // anything at index 1?
Alternatively, you can push something and then delete it:
var a = []
a.push(1)
a.push(2)
a.push(3)
delete a[1]
console.log(a)
console.log(1 in a) // anything at index 1?
There is no need to actually push to a new array in your implementation. You can simply do new Array(this.length) where this.length is the array you are mapping through length.
For example consider this map implementation:
if (!Array.prototype.mapIt) {
Object.defineProperty(Array.prototype, "mapIt", {
value: function(fn) {
if (this === null) {
throw new TypeError('Array.prototype.mapIt called on null or undefined');
}
if (typeof fn !== 'function') {
throw new TypeError('predicate must be a function');
}
let _array = this.filter(x => x != null) // remove empty values
let result = new Array(_array.length) // the new array we will return
for (var i = 0; i < _array.length; i++) {
result[i] = fn.call(arguments[1], _array[i], i, _array) // call the predicate
}
return result;
}
});
}
let arr = [1, 2, , , 3] // the test array
let result = arr.mapIt((c, i, a) =>
console.log(`current: ${c}`, `index: ${i}`, `array: ${a}`) || c + 2)
console.log('result: ', result)
console.log('original array: ', arr)
Hope this helps you with an gives you an idea about a possible map implementation.

How to push new elements to an array with undefined index in JavaScript

I want to create array once and then just push values to it with any index , but i get Cannot read property 'push' of undefined error
I have following scenario
var neg = [];
I want to use push randomly with any index
neg[0].push([1,2]);
or
neg[22].push([1,2]);
right now I want to define manually like neg[0] = []; , Is there any one way where i can just push to any index i want ?
Here's a quick way to do exactly what you want.
var arr = [];
(arr[0]=[]).push([1,2]);
console.log(arr)
Also it's safer to check if an array already exists at this index, otherwise it will be replaced with an empty array – the above code will replace the array with an empty one if it already exists.
// creates an array at index 0 only if there's no array at this index.
// pushes an array of [1, 2] to the existing array at 0 index
// or the newly created empty one.
(arr[0] || (arr[0] = [])).push([1, 2]);;
var arr = [];
arr[0] = [1];
(arr[0]||(arr[0]=[])).push(2,3);
console.log(arr)
Push will add elements to the end of an array. For example:
var neg = [];
neg.push(3); //this will add the number 3 to the end of your array
The problem here is your trying to add a value to an undefined element:
var neg = [];
neg[0].push([1,2]); // <-- neg[0] is not defined at this moment, and you're treating it as an array object.
If you define your elements as an array, you will not get such an error:
var neg = [];
neg[0] = [];
neg[22] = [];
neg[0].push([1,2]);
neg[22].push([1,2]);
Alternatively (and this is probably what you're probably looking for), you can set the value for any element of your array with the desired index:
var neg = [];
neg[0] = [1,2];
neg[22] = [1,2];
You are going to have to set it to an empty array before you can push it.
neg[0] = neg[0] || []
neg[0].push([1,2]);
You can specify how large the array will be if you know ahead of time, for example var neg = new Array(40); will create a new array with 40 undefined elements.
Once that is created, you can change the value at any index as long as 0 <= index <= 39.
You can use array.splice(your_index, 0, your_element); to push an element into an array at the given index.

How to store value pairs in java script?

I need to store the below value pairs like in java script.
(1,1),(1,2),(1,3)(2,1),(2,2),(2,3)
1750 pairs like the above.
I tried using Map but map keys cannot contain duplicates.
Is there any other way i can store these value pairs in java script?
My function using map variable:
function repository()
{
var snakeRepo = new Map();
var xRepo,yRepo,count=0;
for (xRepo = 305;xRepo <=1085;xRepo=xRepo+15)
{
for (yRepo = 55;yRepo <=535;yRepo=yRepo+15)
{
snakeRepo.set(xRepo,yRepo);
//console.log(xRepo+","+yRepo);
count=count+1;
}
}
console.log(snakeRepo);
}
You can have an array inside of an array or objects inside of the array.
Array inside the array
var arrayInArray = [[1,2], [3,4]];
and you can access the values inside the array with:
//where 0 is the index of the values you want
arrayInArray[0]; //returns [1, 2];
Objects inside the array
var objectInArray = [{firstID: 1, secondID: 2},{firstID: 3, secondID: 4}];
and you casn access the values insde with:
where 0 is the index of the object you want
objectInArray[0]; //returns an object {firstID: 1, secondID: 2}
//alternatively, you can access your object's values by adding a dot
objectInArray[0].firstID; // returns 1
To save the date inside the array you can use
arrayInArray.push([1,2]);
objectInArray.push({id1: 1,id2: 2});
I don't know how you want to use it after, but you can store them as object individually ? Then push them in an array if you want :
var pair = {
value1 : 1,
value2 : 2
}
If values are generated in a for loop, it will be easy to use like this.

JavaScript - Array behaves like object

I'd like to ask a question about JavaScript arrays.
Does the array behave like an object when we use for..in loop to iterate. I mean in this case can indexes take the role of properties(keys).
While you can do for..in syntax on an array, you shouldn't because you will will iterate over any properties you may have assigned to the array.
Example:
var array = [0, 1];
array.three = 2;
for (var p in array){
console.log(array[p]); //print 0, 1, 2
}
for(var i = 0; i < array.length; i++){
console.log(array[i]); //prints 0, 1
}
So, when dealing with arrays you should always use the for var i approach to avoid running into unexpected behavior.
As everything in JS, an array is an object.
It means you can use an array as a prototype :
var obj = Object.create([]);
console.log(obj instanceof Array); // true
obj[0] = "value 1";
obj.test = "value of property test";
for(var i in obj) console.log(obj[i]); // "value 1" "value of property test"
or any other thing you would do with an object, including using a for ... in loop.
However, the length property is updated with the highest (integer) index of the array +1.
var arr = ["one","two"];
arr.length; // 2
That's why it's preferred not to use for ... in loops when you only want to iterate on the values of the array : you can use for(var i=0,var l=arr.length;i<arr.length;i++) instead.
Yes ,you can access array like an object Only if array keys are string,
var sdf = [];
sdf['asd'] =45;
sdf[32] =8674;
console.log(sdf.asd) // WORKS
console.log(sdf.32) // Error
Array.prototype.forEach is what you want. Just be mindful of browser support or use a framework that corrects for unsupported browsers: http://kangax.github.io/compat-table/es5/#Array.prototype.forEach
for in should be used for iterating over object properties because order is not guaranteed.

Getting Length of Object in Javascript / jQuery

I am trying to set up an array in jQuery and I then need to do a for loop on it. But it seems that I cant use an associative array for some reason?
var items = new Array();
items['foo'] = 123456;
items['bar'] = 789012;
items['baz'] = 345678;
items['bat'] = 901234;
alert(items.length);
This is just a test, but it return 0?
You can't make associative array in JavaScript like what you want, instead you can use Object.
For example:
var items = {
foo : 123456,
bar : 789012,
baz : 345678,
bat : 901234
}
And to calculate the length you can do:
var getObjectSize = function(obj) {
var len = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) len++;
}
return len;
};
Use: getObjectSize(items); // output: 4
For more see here.
Another one is:
Object.keys(items).length;
But not supported by all browsers.
var items = new Array();
items['foo'] = 123456;
The problem lies in the very first line. You believe that you are adding an item to the array at the index foo, but you are actually adding a property to the items variable with a key foo and value 123456. If you were to type items.foo it would give you back your 123456.
The problem with this approach is that adding a property to an array does not magically increase it's length.
If you want to have non-numeric indexes, you need to use an object instead of an array:
var items = {
foo: 123456,
bar: 789012,
baz: 345678,
bat: 901234
};
Another approach might be to set up two different arrays, which you construct in parallel:
var items = [], items2 = [];
items.push('foo');
items2.push(123456);
// etc.
alert(items2.length);​
The efficiency of this approach depends on how you'll use it. If you're only going to loop through the list of items and do something to each of them, this approach may be more efficient. But if you need to use it like an associative array (items['foo']), then you're better off building an object.
The .length property returns the highest numerical index of the array. Thus, in your case, there is no numerical index and it returns 0. Try
items[98] = "something";
items.length will be 98..! Use the .length property with caution, and if you also want to count the non-numerical indici, loop over the Object (an Array is also an Object) and count its ownProperties.

Categories

Resources