Javascript - loop using IN operator - javascript

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

Related

What is the difference between value in array vs array.includes(value)? [duplicate]

I mean, includes is an Array prototype but in can be used with arrays too, so what is the main difference between both?
Array.includes() checks for the existence of a value in an array, while the in operator checks for the existence of a key in an object (or index in the case of arrays).
Example:
var arr = [5];
console.log('Is 5 is an item in the array: ', arr.includes(5)); // true
console.log('do we have the key 5: ', 5 in arr); // false
console.log('we have the key 0: ', 0 in arr); // true
Array#includes determines whether a given value is an entry in the array. in checks to see if the given string is a known property of the object (or any of its prototypes). They are very different things.
..."in" can be used with arrays too...
It can, to check whether a property with a given name exists, but that's very different from what includes does:
var a = [10];
console.log(a.includes(10)); // true, 10 is an entry in
console.log(10 in a); // false, there's no property called "10" in the array
console.log(0 in a); // true, there IS a property called "0" in the array
Using in on an array is a relatively unusual operation, mostly reserved for use on sparse arrays.
"includes" checks whether a value exists in an array where as "in"
operator checks whether a key/index exists in obj/array.
var arr = [15, 27, 39, 40, 567],
obj = {
num1: 3,
num2: 34,
num3: 89
};;
console.log(arr.includes(27)); // returns true checks 27 as a value in the array
console.log(2 in arr); // returns true checks 2 as index in the array
console.log("num1" in obj); // returns true checks num1 as key in obj
With in operator you can check if key exists, with includes() you can check if value exists

Giving string index with number

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.

Unregistered member of array in length property JS

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.

Sparse arrays and reduce in JavaScript

One would think that in JavaScript:
var array = [1,2,undefined,4];
is the same as:
var array = [1,2];
array.length = 3;
array.push(4);
but it's not. This code shows it:
var array1 = [1,2];
array1.length = 3;
array1.push(4);
var array2 = [1,2,undefined,4];
traverseArray(array1);
traverseArray(array2);
function traverseArray(array) {
console.log("trying: " + array);
console.log("reduce:");
array.reduce(function(prev, current, index, array) {
if(current === undefined) {
console.log("Found undefined");
}
console.log(index+": " +current);
}, undefined);
console.log("for loop:")
for(var i=0;i < array.length;i++) {
var current = array[i];
console.log(i+": " +current);
}
console.log();
}
Output:
trying: 1,2,,4
reduce:
0: 1
1: 2
3: 4
for loop:
0: 1
1: 2
2: undefined
3: 4
trying: 1,2,,4
reduce:
0: 1
1: 2
Found undefined
2: undefined
3: 4
for loop:
0: 1
1: 2
2: undefined
3: 4
Why is undefined in array1 not the same as undefined in array2 and why does the for loop act the same but reduce does not?
array1 has three numerically-named properties: 0, 1, and 3.
array2 has four numerically-named properties: 0, 1, 2, and 3. The value of the property named 2 happens to be undefined.
When you ask an object for the value of a property it doesn't have, the result is undefined.
In the for loop, you ask each array for the values of its properties named 0, 1, 2, and 3. For array1, the property named 2 does not exist, so the property access produces undefined. For array2, the property does exist, but its value actually is undefined, so you get the same result.
On the other hand, reduce only operates on properties that actually exist. From the ECMAScript specification, this is how reduce loops over arrays, using a counter k:
Repeat, while k < len
Let Pk be ToString(k).
Let kPresent be the result of calling the [[HasProperty]] internal method of O with argument Pk.
If kPresent is true, then... [use the value at index k for the reduce call]
So, we can see that an index is only used if passes a [[HasProperty]] check. array1 does not have a property named 2, so that index is skipped.
apsillers nailed it in the comments . . . the difference is that in array2 you have actually assigned an undefined value to the 3rd element in the array (i.e., at index 2), where as, in array1, you have two elements initially, change the length property, and then add a third element in the forth position.
Here are the relevent sections from MDN that explains why the distinction is important:
From the page on Array.length:
When you extend an array by changing its length property, the number of actual elements does not increase; for example, if you set length to 3 when it is currently 2, the array still contains only 2 elements. Thus, the length property says nothing about the number of defined values in the array.
From the page on Array.push():
The push method relies on a length property to determine where to start inserting the given values.
The key here, is really that the length property is really, simple a property that is in no way inherantly tied to the contents of the array. It is simply because the various methods of Array also happen to maintain that property, as they "do their work", that I behaves as if it is.
So, as a result, in array2, the code is actually reporting back the undefined value that you assigned to array2[2], whereas, with array1, the code is interpreting the absence of a value at array1[2] as undefined.

Arrays created with new? [duplicate]

This question already has answers here:
Undefined values in Array(len) initializer
(5 answers)
Closed 7 years ago.
I am confused by the results of mapping over an array created with new:
function returnsFourteen() {
return 14;
}
var a = new Array(4);
> [undefined x 4] in Chrome, [, , , ,] in Firefox
a.map(returnsFourteen);
> [undefined x 4] in Chrome, [, , , ,] in Firefox
var b = [undefined, undefined, undefined, undefined];
> [undefined, undefined, undefined, undefined]
b.map(returnsFourteen);
> [14, 14, 14, 14]
I expected a.map(returnsFourteen) to return [14, 14, 14, 14] (the same as b.map(returnsFourteen), because according to the MDN page on arrays:
If the only argument passed to the Array constructor is an integer
between 0 and 2**32-1 (inclusive), a new JavaScript array is created
with that number of elements.
I interpret that to mean that a should have 4 elements.
What am I missing here?
When you create an array like so:
var arr1 = new Array( 4 );
you get an array that has a length of 4, but that has no elements. That's why map doesn't tranform the array - the array has no elements to be transformed.
On the other hand, if you do:
var arr2 = [ undefined, undefined, undefined, undefined ];
you get and array that also has a length of 4, but that does have 4 elements.
Notice the difference between having no elements, and having elements which values are undefined. Unfortunately, the property accessor expression will evaluate to the undefined value in both cases, so:
arr1[0] // undefined
arr2[0] // undefined
However, there is a way to differentiate these two arrays:
'0' in arr1 // false
'0' in arr2 // true
var a = new Array(4);
This defines a new array object with an explicit length of 4, but no elements.
var b = [undefined, undefined, undefined, undefined];
This defines a new array object with an implicit length of 4, with 4 elements, each with the value undefined.
From the docs:
callback is invoked only for indexes of the array which have assigned
values; it is not invoked for indexes which have been deleted or which
have never been assigned values.
For array a, there are no elements that have been assigned values, so it does nothing.
For array b, there are four elements that have been assigned values (yes, undefined is a value), so it maps all four elements to the number 14.
new Array(len) creates an empty array, and does something different than filling it with undefined values: It sets its length to len. So, it translates to this code:
var newArr = [];
newArr.length = len;
Let's have some fun with newArr (assuming that len = 4):
newArr.length; //4
newArr[1] === undefined; //true
newArr.hasOwnProperty(1); //false
This is because while the is 4 items long, it does not contain any of these 4 items. Imagine an empty bullet-clip: It has space for, say, 20 bullets, but it doesn't contain any of them. They weren't even set to the value undefined, they just are...undefined (which is a bit confusing.)
Now, Array.prototype.map happily walks along your first array, chirping and whistling, and every time it sees an array item, it calls a function on it. But, as it walks along the empty bullet-clip, it sees no bullets. Sure, there are room for bullets, but that doesn't make them exist. In here, there is no value, because the key which maps to that value does not exist.
For the second array, which is filled with undefined values, the value is undefined, and so is the key. There is something inside b[1] or b[3], but that something isn't defined; but Array.prototype.map doesn't care, it'll operate on any value, as long as it has a key.
For further inspection in the spec:
new Array(len) : http://es5.github.com/#x15.4.2.2
Array.prototype.map : http://es5.github.com/#x15.4.4.19 (pay close attention to step 8.b)
One additional answer on the behavior of console.log. Plain simple, the output is sugar and technically wrong.
Lets consider this example:
var foo = new Array(4),
bar = [undefined, undefined, undefined, undefined];
console.log( Object.getOwnPropertyNames(bar) );
console.log( Object.getOwnPropertyNames(foo) );
As we can see in the result, the .getOwnPropertyNames function returns
["length"]
for the foo Array/Object, but
["length", "0", "1", "2", "3"]
for the bar Array/Object.
So, the console.log just fools you on outputting Arrays which just have a defined .length but no real property assignments.

Categories