JavaScript ES6: Split array into rest and last with destructuring [duplicate] - javascript

This question already has answers here:
Destructuring to get the last element of an array in es6
(17 answers)
Closed 5 years ago.
I just discovered the delightful ES6 destructuring syntax for lists, i.e.
ls = [1, 2, 3]
[first, ...rest] = ls
which sets first to 1 and rest to [2,3]. However, is it possible to split the list into rest=[1,2] and last=3 using similar syntax?
I didn't have any luck googling it. I tried some obvious guesses for such a syntax (see below), but they all produced syntax errors.
[rest..., last] = ls
[...rest, last] = ls
I suppose I could do it by reversing the list twice, so an alternate solution to my question would be a constant time list reversal function.

What is commonly called "array destructuring" is actually destructuring an iterable, of which an array is a special case. The thing about iterables is that they can be infinite, or "lazy". That is the reason that you cannot destructure into some arbitrary number of elements followed by the last one:
const [...first, last] = integers();
because integers could be
function* integers() {
let n = 0;
while (true) yield n++;
}
and then what would last be?

No, this only works on trailing array elements. So, as you said, they way to achieve what you want would be reversing the array first.
Just in case you haven't come across a similar pattern for object, there is one:
const {a, ...rest} = {a: "prop1", b: "prop2", c: "prop3"}
A great tool to try all this new features out is https://babeljs.io/repl

Related

How to print JavaScript array with set of pairs inside array [duplicate]

This question already has answers here:
JavaScript expressions, comma delimited within parentheses [duplicate]
(3 answers)
Closed 2 years ago.
I was going through documentation of JavaScript about arrays and objects.I found one unique query about arrays
var a= [1,2,3]
console.log(a) // give [1,2,3]
var b = [(1,2) , (3,4) , (5,6)]
console.log(b) // gives [2,4,6]
I didn't understand the logic behind the same.It just ran over my mind.If we do same thing in python
a = [(1,2),(3,4)]
print(a) // [(1,2),(3,4)]
Can some one explain the same and can someone explain me how to get the same output in JavaScript like the way I got in python.How to iterate through all the elements in array in javascript
I'm not a Python programmer, but those parentheses differ in their functionality between Python and JavaScript.
I understand in Python they indicate a tuple literal. In JavaScript, they merely group things they say "execute each statement and return the last one." That's why you only see some items in your JS arrays.
See also https://stackoverflow.com/a/25280412/1371131
What you have encountered is the comma operator.
When there is no other context, a , in an expression behaves like an operator just like + or = or / etc.
The comma operator behaves as follows:
evaluate the first expression
ignore the result of the first expression
evaluate the second expression
return the value of the second expression
Thus the following code:
a = 1,2;
b = 1,2,3,4;
will result in a being assigned the value 2 and b assigned the value 4.
This may seem kind of silly because we already have ; but the comma operator is useful if you need more than one thing to happen in a single expression context. For example if you need more than one thing to happen in one of the conditions of a for loop you cannot use ; because that is used to separate the conditional expressions. The comma operator comes to the rescue:
for (let a = 0, b = 0; a < 10; a++, b++) { //...
// ^ ^
// | |____ two things happen here
// |_______________________________ and here
So (1,2) is just another way to write 2.
Therefore [(1,2) , (3,4) , (5,6)] and [2,4,6] is the same array.
Just like [1+1, 2+2, 3+3] and [2,4,6] is the same array.
They are just different ways to write [2,4,6]. The same way you cannot loop through the array and extract 1+ from [1+1, 2+2, 3+3] you cannot loop through the array and extract (1, from [(1,2) , (3,4) , (5,6)].
If you really need an array of pairs you need to use an array of arrays:
a = [[1,2],[3,4],[5,6]]

JavaScript weirdness [duplicate]

This question already has answers here:
What is the difference between ( for... in ) and ( for... of ) statements?
(18 answers)
Closed 2 years ago.
Could someone explain me why it prints [ '01', '11', '21' ]. I'm normally a java - Python - PHP dev
function g(element){
return element + 1;
}
function f(points, g){
let newArray = [];
for(let point in points){
newArray.push(g(point));
}
return newArray;
}
let array = [1, 2, 3];
console.log(f(array, g));
Yes, this is a javascript weirdness.
At first, the for in loop will iterate over the indizes, not the content of the array. This is "0", "1", "2".
The indizes do also seem to be interpreted as strings.
"0"+1=01
"1"+1=11
"2"+1=21
You are looping of the Keys by using in keyword in your for statement, To loop over array items use of keyword.
So your loop will be like this:
for(let point of points){
newArray.push(g(point));
}
The output looks as if the input array was ["0","1","2"] and not [1,2,3].
The mistake here is that the syntax for..in in javascript is used to loop through the keys/indexes of an object/array, not its values.
Something to notice here (which I did't know before and checked) is that the indexes of the array are converted to string when using a for..in, that's why the numbers were concatenated rather than summed.
Anyway, one correct syntax to loop through the elements of an array is the for..of syntax, which is used just like the for..in syntax and behaves as you expected.

How do you ignore an item when destructuring an array? [duplicate]

This question already has answers here:
How can I ignore certain returned values from array destructuring?
(2 answers)
Closed 4 years ago.
I'm self-answering this because I didn't come across a question or answer that discussed ignoring a destructured array element while searching.
Is there a way to ignore an element of a array when destructuring? The closest thing that I can think of is how in Go you can use the _ symbol to drop an argument.
I'm using ESLint and I'd like to be able to avoid unused variable warnings without having to explicitly turn off the warning. I also don't like the scope leak even though it is rather minimal.
For example:
const arr = [
["foo", "bar"],
["fizz", "buzz"],
["hello", "world"]
];
// I don't actually want 'a' to be available in the scope
arr.forEach(([a, b]) => console.log(`a: ${a} | b: ${b}`));
// _ is still defined and equates to 'a' above
arr.forEach(([_, b]) => console.log(`'a': ${_} | b: ${b}`));
You can ignore an element by simply not providing a variable for the value to be assigned to and just putting the comma as though you had. See MDN: Destructuring assignment#Ignoring some returned values.
For example:
const arr = [
["foo", "bar"],
["fizz", "buzz"],
["hello", "world"]
];
// Just use ','
arr.forEach(([, b]) => {
// No variable is populated with the first element
console.log(typeof(a));
console.log(typeof(b));
console.log(`b: ${b}`);
});

Unfamiliar use of square brackets during multiple variable declaration in Javascript [duplicate]

This question already has answers here:
Multiple assignment in JavaScript? What does `[ a, b, c ] = [ 1, 2, 3 ]` mean?
(4 answers)
Closed 5 years ago.
I'm a beginner to Javascript and encountered this syntax usage(simplified):
var testString ="firstName, lastName";
var [a,b] = testString.split(", ");
My question is what typeof variable a & b then becomes at line2?
My simplistic investigation seems to indicate a & b are assigned respective string values.
But what goes on under the hood? why do we use square brackets [] here? Isn't an array returned & created in the process by .split()? Otherwise, what objects were created in the background?
Links to understand this style of declaration for [a,b] would also be welcomed.
But what goes on under the hood?
// You declare a string variable
var testString = "firstName, lastName";
// Split method help you to divide the string value according with the
//indicated separator, in this examle the comma
var [a,b] = testString.split(", ");
The destructuring assignment syntax is a JavaScript expression that
makes it possible to unpack values from arrays, or properties from
objects, into distinct variables.
Since the split function returns an array, with the var [a,b] = array
you are assigning the value in index order, in the example:
console.log(a); // 'firstName'
console.log(b); // 'lastName'
And they are simple string variables. You may want to vist the links below:
Destructuring asignation
split function
Further resources: Since you have mentioned you are beginning with JS, I suggest you to read books mentioned in this magnific post
This is destructuring assignment. It resembles the pattern-matching found in many functional languages.

Javascript. Assign array values to multiple variables? [duplicate]

This question already has answers here:
Multiple assignment in JavaScript? What does `[ a, b, c ] = [ 1, 2, 3 ]` mean?
(4 answers)
Closed 7 years ago.
var a,b,c;
var arr = [1,2,3];
[a,b,c] = arr;
this code works perfectly in Firefox resulting a=1, b=2 and c=3,
but it doesn't work in Chrome. Is it a Chrome bug or
it is not valid javascript code? (I failed to find it in javascript references)
How can I modify this code to make it suitable for Chrome, with minimum damage to it?
(I don't really like to write a = arr[0]; b = arr[1]... or the same with arr.shift() all the time)
P.S. this is just an example code, in real code
I get the arr array from somewhere outside my code
This is a new feature of JavaScript 1.7 called Destructuring assignment:
Destructuring assignment makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.
The object and array literal expressions provide an easy way to create ad-hoc packages of data. Once you've created these packages of data, you can use them any way you want to. You can even return them from functions.
One particularly useful thing you can do with destructuring assignment is to read an entire structure in a single statement, although there are a number of interesting things you can do with them, as shown in the section full of examples that follows.
You can use destructuring assignment, for example, to swap values:
var a = 1;
var b = 3;
[a, b] = [b, a];
This capability is similar to features present in languages such as Perl and Python.
Unfortunately, according to this table of versions, JavaScript 1.7 has not been implemented in Chrome. But it should be there in:
FireFox 2.0+
IE 9
Opera 11.50.
Try it for yourself in this jsfiddle: http://jsfiddle.net/uBReg/
I tested this on Chrome (failed), IE 8 (failed), and FireFox 5 (which worked, per the wiki table).
It is possible only for Javascript 1.7 as already answered by #Justin. Here is a trial to simulate it in the widespread browsers:
function assign(arr, vars) {
var x = {};
var num = Math.min(arr.length, vars.length);
for (var i = 0; i < num; ++i) {
x[vars[i]] = arr[i];
}
return x;
}
var arr = [1, 2, 3];
var x = assign(arr, ['a', 'b', 'c']);
var z = x.a + x.b + x.c; // z == 6
I don't know how useful it is.

Categories