I was testing giving index as a string to array. But I noticed that array converts string index to number.
for example: A["1"] turns to with A[1]
Can I give a number as a string to array index?
A["1"] = 1;
A["3"] = 3;
expected output:
[ 1: 1, 3: 3 ]
output:
[ <1 empty item>, 1, <1 empty item>, 3 ]
like as usual string index arrays;
A["a"] = 1;
A["c"] = 3;
output:
[ a: 1, c: 3 ]
I think you are confusing objects and arrays.
An array is just a list of items:
const array = [1,2,3,4,5]
// You can access its items by index:
array[0] => 1
array['1'] => 2
An object is a list of key-value pairs and keys are strings:
const obj = { a: 1, b: 2 }
// You can access its item values by key:
array.a => 1
array['b'] => 2
All property names are strings, So array like numeric property names really aren't any different from any other property names.
Javascript arrays cannot have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object.
A.a = '1' and A['a'] = '1' are equals.
So I think you need to use object. You can do this to get the same output.
function test() {
// A["1"] = 1;
// A["3"] = 3;
let A = {
1: 1,
3: 3
};
return A;
}
output
{ '1': 1, '3': 3 }
Everything in JavaScript is an Object.
Array too. It's just has some special properties and notation. An array is an Object where values are stored in key value pair. Keys are index of an array and values are elements.
For example:
const a = [1,2,4,6]
Object.keys(a) // iterating through keys will give you indexes [0,1,2,3]
There is just one catch. If you provide index of an array as non negative Integer, it will push value to array else all values will be associated as object.
So
a["a"]=1 // [1,2,4,6, a:1], length of an array will be 4 and key a can be accessed as property
Hope it helps.
Related
My array is
arrays = [1, 2, 3]
index for array is
arrays = [ 0:1 , 1:2, 2:3 ]
my variable is
id = 3
I have to check if 3 is in array and 3 is in the index value of 2.
I am using for loop
for (let z in this.arrays){
if (id in this.arrays[z]){
console.log("duplicate")
}
}
but I got an error
ERROR TypeError: Cannot use 'in' operator to search for '2' in 1
How to do that using javascript
You need to understand about "in" operator first. The in operator returns true if the specified property is in the specified object or its prototype chain or in an Array. How to use this for Array (sample reference here ):
// Arrays
let trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']
0 in trees // returns true
3 in trees // returns true
6 in trees // returns false
'bay' in trees // returns false (you must specify the index number, not the value at that index)
'length' in trees // returns true (length is an Array property)
Symbol.iterator in trees // returns true (arrays are iterable, works only in ES2015+)
// Predefined objects
'PI' in Math // returns true
// Custom objects
let mycar = {make: 'Honda', model: 'Accord', year: 1998}
'make' in mycar // returns true
'model' in mycar // returns true
What you're checking on Array is the key, which is its index. You should use find method in array to find any values instead of "in":
const arrays=[ 1 , 2, 3 ];
const arrays_1=[ 1 , 2, 3, 3, 4, 3 ];
const found = arrays.find(el => el === 3); // it will return the first value if it matches the condition.
const found_all = arrays_1.filter(el => el === 3); // will give all the matching values.
The problem is that you are trying to use the in operator on an array value instead of on the array itself.
Do something like this:
for( let z in arrays){
if( 2 in arrays && z == 2 && arrays[z] == 3) console.log("duplicate");
}
Check the following link for an in depth explanation on the “in” operator:
https://www.google.com/amp/s/www.freecodecamp.org/news/the-javascript-in-operator-explained-with-examples/amp/
id in this.arrays[z]
because arrays[z] must be array or object.
In checks for key existence
I am really confused about this 2D array.
For example:
let arr = Array(2)
arr.fill(Array(2))
arr[0][0]=1
And the result of arr is [1,empty][1,empty]
Why is it like that?
I just want the first item in the first array to be set as 1
Because you use 1 instance of an array to fill you first array (arr). So arr[0] and arr[1] are actually the same instance, they point to the same address.
If you want to fill you array arr with new arrays, loop over you first array arr, and then assign them new array.
const arr = Array(2);
for (let i = 0; i < arr.length; i++) {
arr[i] = Array(2);
}
arr[0][0] = 1;
Array(2) is the empty array that is copied to each element of arr.
But all the copies of Array(2) are the deep-copies.
So, changes in one of the deep-copy will be reflected in all the copies of Array(2).
let arr = Array(2)
arr.fill(Array(2))
arr[0][0]= 1
// [ [ 1, <1 empty item> ], [ 1, <1 empty item> ] ]
arr[0][1] = 2
// [ [ 1, 2 ], [ 1, 2 ] ]
The docu says...
Value to fill the array with. (Note all elements in the array will be this exact value.)
That means they share the same adress in memory.
You need a different approach to fill your array..
let arr = Array.from({length: 2}, e => Array(2))
arr[0][0]=1
console.log(arr);
I came across this code that is used to keep both forward and reverse reference in an array:
var arr = [];
arr[arr['A'] = 0] = 'A';
arr[arr['B'] = 1] = 'B';
// On node interpreter
arr // [ 'A', 'B', A: 0, B: 1 ]
arr["A"] // 0
arr["B"] // 1
arr[0] // 'A'
arr[1] // 'B'
arr[2] // 'undefined'
arr.length // 2
The A: 0, B: 1 members get pushed to the end of the array.
What are these members and what happened in the process so that .length property recorded 2 instead of 4?
Storing a value with a string key into an array does not actually modify the array. It only adds a dynamic field to the Array object, unlike storing with a numeric index, which actually pushes a value into the array.. Array.length only reflects the number of elements in the array, as managed by the array, but not the number of dynamic fields in the array.
var arr = [];
arr["A"] = 2;
Here you are adding a property to the array object which does not reflect over the number of elements in the array.In javascript, elements of array are always stored using indices.
Array.length always returns the number of elements stored in the array.
I am new to JavaScript and I am having trouble working with my array, I want my array ordered how I explicitly write it and not how JavaScript decides it wants it.
If we have a array
var array = {
0: 'zero',
4: 'four',
2: 'two'
};
When I choose to display this in the console, or iterate over it, Its reordered like this
array = {
0: 'zero',
2: 'two',
4: 'four'
};
I have tried 2 loops so far, The for loop, and also the for loop with the in statement.
Both work according how I assumed they would as they use a key and work there way up/down, making order I specify is absolutely useless.
How can I write/print/work with my array as its ordered, In other languages such as PHP its as simple as
$array = array(
0 => 'zero',
4 => 'four',
2 => 'two'
);
foreach($array as $key => $value)
echo $key ."\n";
This would output
0
4
2
Thanks in advance.
You're using an object {}, not an array []. Objects have no explicit order, where Arrays do. That's why you're having your problem. Change your {} to [] and you'll be fine. You could even use an array of objects.
var array = [
{0: 'zero'},
{4: 'four'},
{2: 'two'}
];
Looping over that like so
for(var i = 0; i < array.length; i++){
console.log(array[i]);
}
Gives us our normal order.
Object {0: "zero"}
Object {4: "four"}
Object {2: "two"}
Another Edit: The problem is you're trying to have an array that has properties and values just like an object, without using an object, {property: value} - that can't really be done with an array. To loop over an array like you want, it's as simple as
var arr = [1,2,3]
and
for(var i = 0; i < arr.length; i++){
console.log(i) //1,2,3
}
but the problem, like mentioned above, is you want more complex arrays which you simply can't do.
You need to understand what an Array and what an Object are, they are fundamentally different things and do not behave the same.
Array
Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed. Since an array's size length grow or shrink at any time, JavaScript arrays are not guaranteed to be dense. In general, these are convenient characteristics; but if these features are not desirable for your particular use, you might consider using typed arrays.
Examples of an Array, note the magical length property, the values assigned to an Array are always found at their indexed locations; index is from 0 to 2^32 - 1
// dense arrays
var array1 = [1, 2, 3];
array1.length === 3;
array1[0] === 1;
var array2 = [];
array2[0] = 1;
array2[1] = 2;
array2[2] = 3;
array2.length === 3;
array1[1] === 2;
var array3 = [];
array3.push(1);
array3.push(2);
array3.push(3);
array3.length === 3;
array3[2] === 3;
// and a sparse array
var array4 = [];
array4[0] = 1;
array4[2] = 2;
array4[4] = 3;
array4.length === 5;
array4[1] === undefined;
Iterating an array for
var array = [1, 2, 3, 4, 5];
for (var index = 0; index < array.length; index += 1) { // counts from (index) 0 to 4
console.log(index, array[index]); // outputs 0 1 \n 1 2 \n 2 3 \n 3 4 \n 4 5
}
Object
An object is a collection of properties, and a property is an association between a name and a value. A property's value can be a function, in which case the property is known as a method. In addition to objects that are predefined in the browser, you can define your own objects.
Examples of an Object, there is no magical length property.
var object1 = {
'zero': 1,
'one': 2,
'two': 3
};
object1.zero === 1;
var object2 = {);
object2['zero'] = 1;
object2['one'] = 2;
object2['two'] = 3;
object2.one === 2;
var object3 = {);
object3.zero = 1;
object3.one = 2;
object3.two = 3;
object['two'] === 3;
Iterating (enumerating) an object for..in
var object = {
one: 0,
two: 1,
three: 2
};
for (var property in object) {
if (object.hasOwnProperty(property)) { // make sure the property belongs to object
console.log(property, object[property]); // outputs (not necessarily this order)
// three 2 \n two 1 \n one 0
}
};
If you are trying to maintain an ordered Object, then this is not how Javascript works and iteration (enumeration) of an object is arbitrary. There are techniques that you can use to iterate (enumerate) an Object in a known order. This requires that you keep an ordered list of properties in an array and use the array in the iteration process.
var object = {
'c': 1,
'z': 2,
'b': 3,
'a': 4
}
var propertyOrder = ['c', 'z', 'b', 'a'];
for (var index = 0; index < propertyOrder.length; index += 1) {
console.log(index, propertyOrder[index], object[propertyOrder[index]]); // outputs 0 c 1 \n 1 z 2 \n 2 b 3 \n 3 a 4
}
I don't get it. What makes you think that 0, then 4, then 2, is in any form or shape "in order"?
However, apparently what you want is to keep the number and the string together, in the order that you specify.
Your mistake, if you'll excuse me for perhaps sounding a bit harsh, is that you seem to think that you can use indices or member names to be both a means to access data and part of the data itself.
You can't, and you shouldn't. An index is an index, a name is a name, and data is data [1].
Here are two implementations of keeping your numbers and strings together:
var pairs = [
[0, "zero"],
[4, "four"],
[2, "two"]
];
for (var index in pairs) {
alert(pairs[index][0] + ": " + pairs[index][1]);
};
For this one, I keep the pairs of numbers and strings together in arrays of their own: the numbers at position 0, the strings at position 1. I store these arrays in pairs.
Then I iterate over array with for/in, which, in each iteration, gives me an index of my pairs array.
I then use that index to access the right sub-array in pairs, and get the number from position 0 and the string from position 1.
var pairs = [
{number: 0, string: "zero"},
{number: 4, string: "four"},
{number: 2, string: "two"}
];
for (var index in pairs) {
alert(pairs[index].number + ": " + pairs[index].string);
};
This one works exactly the same, except of storing the pairs in arrays, I store them in objects.
This has the added bonus of better readability inside the for loop: pairs[index][0] and pairs[index][1] do not really convey a clear meaning. It tells us nothing more than, "of the pair with the given index, get items 0 and 1".
However, pairs[index].number and pairs[index].name are much clearer: "of the pair with the given index, give me the number and the name."
_
Footnotes:
[1a] A number is a number: my bank account number is just that: a means to identify my bank account. It doesn't convey any meaning as to my name, my PIN, or the balance on my account -- all attributes that would qualify as data belonging to my bank account.
[1b] A name is a name: my name is just a name. When you're talking about me, you can use my name to refer to me, so that others know whom you are talking about. My name does not convey any information about my hobbies, my SSN, or what brand of car I have -- all attributes that would qualify as data that would describe certain aspects of me. (However, by convention, you can often tell a person's gender by their name)
When using strings as keys of an array, console is showing that the array without these declared values and while iterating by this values where keys are string aren't displayed? , although i can get value of them.
>> var arr = [ 0, 1, 2, 3 ];
undefined
>> arr["something"] = "aught";
"aught"
>> arr
[0, 1, 2, 3]
>> arr["something"]
"aught"
>> for( var i = arr.length; i--; console.log( arr[ i ] ) );
3
2
1
0
I understand that arrays are objects which has implemented some kind of 'enumerate' interface in JavaScript's engine.
Most interesting is that interpreter isn't throwing either warning or error, so I spent some time of searching for where data could be lost.
In javascript there are 2 type of arrays: standard arrays and associative arrays
[ ] - standard array - 0 based integer indexes only
{ } - associative array - javascript objects where keys can be any strings
So when you define:
var arr = [ 0, 1, 2, 3 ];
you are defining a standard array where indexes can only be integers. When you do arr["something"] since something (which is what you use as index) is not an integer you are basically defining a property to the arr object (everything is object in javascript). But you are not adding an element to the standard array.
for( var i = arr.length; i--; console.log( arr[ i ] ) );
This will only give you the numeric indices, of course, but you can still loop over both numeric indices and string keys of your array like this:
for (var x in arr) {
console.log(x + ": " + arr[x]);
}
/* (console output):
0: 0
1: 1
2: 2
3: 3
something: aught
*/