JavaScript destructuring with an array element - javascript

I have met the following questions in JavaScript:
const [x1, ...[result]] = [3, 4, 5]
console.log([result])
I know x1 is 3, but why is the logging result [4] instead of [4,5]?

So basically what is happening if we follow this syntax
const [a,...b] = [3,4,5]
Javascript creates an array called b and has the value [4,5]
But in your case what is happening is,
const [a,...[b]] = [3,4,5]
This is essentially assigning to only the first variable of the empty array with first value as b, which always equals 4 and not [4,5] as you expect.
So it's equivalent to the case below
const [a,...[b,c]] = [3,4,5]
the only difference is that you are not providing a variable c in your case.
So b would correspond to 4 and c would correspond to 5

Related

Check if an array includes an array in javascript

The javascript includes function can be used to find if an element is present in an array. Take the following example:
var arr = ['hello', 2, 4, [1, 2]];
console.log( arr.includes('hello') );
console.log( arr.includes(2) );
console.log( arr.includes(3) );
console.log( arr.includes([1, 2]) );
Passing 'hello' or 2 to the function returns true, as both are present in the array arr.
Passing 3 to the function returns false because it is not present in the array.
However, why does arr.includes([1, 2]) return false as well, even though this is equal to the last element in the array? And if this method does not work, how else can I find whether my array includes the item [1, 2]?
.includes() method uses sameValueZero equality algorithm to determine whether an element is present in an array or not.
When the two values being compared are not numbers, sameValueZero algorithm uses SameValueNonNumber algorithm. This algorithm consists of 8 steps and the last step is relevant to your code , i.e. when comparison is made between two objects. This step is:
Return true if x and y are the same Object value. Otherwise, return false.
So in case of objects, SameValueZero algorithm returns true only if the two objects are same.
In your code, since the array [1, 2] inside arr array is identically different to [1, 2] that you passed to .includes() method, .includes() method can't find the array inside arr and as a result returns false.
The Array#includes checks by shallow comparison, so in your case the string and numbers are primitives there is only ever a single instance of them so you get true from Array#includes.
But when you check for array, you are passing a new array instance which is not the same instance in the array you are checking so shallow comparison fails.
To check for an array is included in another array first check if it is an array then do a deep comparison between the arrays.
Note that below snippet only works for an array of primitives:
var arr = ['hello', 2, 4, [1, 2]];
const includesArray = (data, arr) => {
return data.some(e => Array.isArray(e) && e.every((o, i) => Object.is(arr[i], o)));
}
console.log(includesArray(arr, [1, 2]));
But if you keep the reference to the array [1, 2] and search with the reference the Array#includes works as in this case the shallow comparison works perfectly (obeying same value zero algorithm):
const child = [1, 2];
const arr = ['hello', 2, 4, child];
console.log(arr.includes(child));
If you don't mind using lodash, this algorithm is accurate - unlike the accepted answer.
import _ from 'lodash';
export const includesArray = (haystack, needle) => {
for (let arr of haystack)
if (_.isEqual(arr, needle)) {
return true
}
return false
}

Problem with Accesing array data Javascript

I want to access data of var a so it is: 245 but instead it only accesses the last one. so if i print it out it says 5
var A = [1, 2, 3, 4, 5];
var B = A[[1], [3], [4]];
console.log(B)
When accessing an object using square bracket notation — object[expression] — the expression resolves to the string name of the property.
The expression [1], [3], [4] consists of three array literals separated by comma operators. So it becomes [4]. Then it gets converted to a string: "4". Hence your result.
JavaScript doesn't have any syntax for picking non-contiguous members of an array in a single operation. (For contiguous members you have the slice method.)
You need to get the values one by one.
var A = [1, 2, 3, 4, 5];
var B = [A[1], A[3], A[4]];
console.log(B.join(""))
var A = [1, 2, 3, 4, 5];
var B = [A[1], A[3], A[4]];
console.log(B)
You'll need to access A multiple times for each index.
var A = [1, 2, 3, 4, 5];
var B = A[1];
console.log(A[1], A[3], A[4])
You can access them directly like that.
If you want to access index 2 for example, you should do console.log(A[1]);
You can't access multiple indices at the same time.
A variable can have only one value.
#Quentin solution resolve the problem, I wrote this solution to recommend you to create an array of index, and iterate over it.
Note: You are getting the last index, because you are using the comma operator. The comma operator allows you to put multiple expressions. The resulting will be the value of the last comma separated expression.
const A = [1, 2, 3, 4, 5];
const indexes = [1,3,4];
const B = indexes.map(i => A[i]).join``;
console.log(B);

Javascript copying an array of arrays [duplicate]

This question already has answers here:
Create copy of multi-dimensional array, not reference - JavaScript
(4 answers)
Closed 8 months ago.
I want to copy an array of arrays at a different allocation.
I know that I can copy an array in the following way:
a = [[1, 2], [3, 4]]
b = a.slice() // this makes sure that a and b are allocated differently in memory
Now if I change something inside b, then of course,
b[0] = 'abc'
console.log(a, b) // expect a = [[1,2], [3,4]] and b = ['abc', [3,4]]
But when I do the below, a gets changed as well...!
b[0][0] = 'abc'
console.log(a, b) // now it gives a = [['abc', 2], [3, 4]] and b = [['abc', 2], [3, 4]]
Why is this happening, and how can I avoid mutating a?
Thanks so much!
If you know you are only copying 2D arrays you could use a function like the following and avoid using JSON:
function copy2D(array){
result = []
array.forEach((subArray) => {
result.push(subArray.slice())
})
return result
}
One way would be by using map combined with the spread operator. This would be the easiest approach if you can assume that you have a 2D array only
const a = [[1, 2], [3, 4]]
const b= a.map(item => ([...item]))
b[0][0]= "abc"
console.log('a:', a, 'b: ', b)

JavaScript Destructuring

I was looking for info on JavaScript destructuring and found the video "Destructuring Assignment" as part of a video series from Packt Publication. At the very beginning of the video, I saw the following code:
var [a, b] = [1,2,3];
a === 1;
b === 3;
The presenter then explains why variable b is 3 and not 2, which didn't seem correct to me, but I thought maybe I'm wrong.
So I did a Code Pen with the following code:
var [a, b] = [1,2,3]
console.log(a,b) //1 2
As I expected, the variable b is 2.
Is there something I'm missing and not understanding?
Below is a screenshot of the video in questions.
Yes, the video is wrong, these below are the only ways to get the 3 in this array (using two variables names):
const [a, , b] = [1, 2, 3]; // b is 3
const [a, ...b] = [1, 2, 3]; // b is [2, 3], so b[1] is 3
Also, see: Destructuring to get the last element of an array in es6

Why do objects changed in function change what they point to in memory, but sometimes create a new memory object? [duplicate]

This question already has answers here:
JavaScript by reference vs. by value [duplicate]
(4 answers)
Closed 8 years ago.
I was reading on this blog about how if an object or array were changed inside of a function, the value in memory that was pointed to would be changed as well, the same as if it were changed outside the function.
var a = [1,2,3],
b = a;
b[0] = 5;
console.log(a); // [5, 2, 3]
would result in the same as
var a = [1,2,3],
b = a;
var arrayFunction = function(arr){
arr[0] = 10;
};
var arr = arrayFunction(b);
console.log(a, b, arr) // [10, 2, 3], [10, 2, 3], [10, 2, 3];
Yet what I can't understand is why reassigning multiple array values within the function does not change the values outside of it:
var a = [1,2,3],
b = a;
var arrayFunction = function(arr){
arr = ["a", "b", "c"];
return arr;
};
var result = arrayFunction(b);
console.log(result) //["a", "b", "c"]
console.log(a, b); //[1, 2, 3], [1, 2, 3]
Why does this not change the pointed to value in memory like in the first example?
Probably a better job of writing out the examples on the JSBIN
This is because objects in javascript aren't really passed by reference. I've seen it referred to as "passed by copied reference", or "passed by handle" - both of which do a better job of describing what's really happening.
In this example:
var b = [1, 2, 3];
var arrayFunction = function(arr) {
arr = ["a", "b", "c"];
};
arrayFunction(b);
The object reference itself is passed by value. You're not actually changing the value of the b variable. However, your function argument (arr) and the b variable are initially pointing to the same object - so if you change one, you can reference the object through either and see the change.
When you reassign arr to point to a different object though, the b variable is still pointing to the old object, and does not change.
Remember that, within the function, arr is not the actual array; arr is a reference that points to the array.
So when you say arr[0], you're retrieving the array, and then getting or updating an item in it.
But when you say arr = ["a","b","c"], you are creating a new object (on the right side) and then turning arr into a reference that points to the new object.
In Javascript a variable merely points to an array; so if you copy the variable you get two variables pointing to the same array:
var a = [1,2,3];
var b = a;
Changing an element of the array with a[0] = 99 will be observable with both variables because there is just one array and both a and b are pointing to it.
When you write instead
a = [5, 6, 7];
you are setting a to point to another different array.
Javascript never makes a copy of an array unless you ask it explicitly (e.g. with b = a.slice()).
Actually the very same happens with any value (objects for example). With numbers and string the same logic is also valid, but it's hard to notice the difference between a copy and sharing the same object because numbers and strings cannot be changed (the're "immutable").
In other languages like C and C++ instead variables contain the value, not a pointer; so when making an assignment for example objects are copied from one variable to the other and if you want a pointer you've to ask explicitly for it.

Categories

Resources