Reputation: 956
In the below example, unmapped array items must be mapped to rest parameter in the left hand side, but for some reason the output is different,
var planets = ["Mercury", "Earth", "Venus", "Mars", "Pluto", "Saturn"];
var [first, second, ...rest] = ["Mercury", "Earth", ...planets, "Saturn"];
console.log(first); //Output: Mercury
console.log(second); //Output: Earth
Now for the below, expected output is,
console.log(rest); //Output: ["Venus", "Mars", "Pluto", "Saturn"]
But the actual output is,
console.log(rest); //Output: "Mercury", "Earth", "Venus", "Mars", "Pluto", "Saturn", "Saturn"
Source:https://www.freecodecamp.org/news/array-destructuring-in-es6-30e398f21d10/
Whats happening here?
Upvotes: 1
Views: 63
Reputation: 37755
You can spread selectively. When you spread ...planets
it copies all the values from planets array to the array you're creating.
You can simply use slice before spreading.
var planets = ["Mercury", "Earth", "Venus", "Mars", "Pluto", "Saturn"];
var [first, second, ...rest] = ["Mercury", "Earth", ...planets.slice(2, planets.length - 1), "Saturn"];
console.log(first);
console.log(second);
console.log(rest)
Upvotes: 1
Reputation: 50854
When you spread planet into your your second array, you're putting all the elemtns from the planets
array into the second array, so:
["Mercury", "Earth", ...planets, "Saturn"];
... evaluates to:
["Mercury", "Earth", "Mercury", "Earth", "Venus", "Mars", "Pluto", "Saturn", "Saturn"];
you then destructure the first and second elements from this array giving you "Mercury"
and "Earth"
. You then use the rest pattern ...rest
to retrieve the remaining elements (ie elements from index 2 and onwards) and store them in the array named rest
. Thus, your rest
array contains all the elements from the array above, excluding the first and second elements:
["Mercury", "Earth", "Venus", "Mars", "Pluto", "Saturn", "Saturn"]
To do get your expected output, you can destucture the first array, by ignoring the first two elements:
const [,,...rest] = ["Mercury", "Earth", "Venus", "Mars", "Pluto", "Saturn"];
console.log(rest);
Upvotes: 2
Reputation: 20039
You can use Set()
The Set object lets you store unique values
var planets = ["Mercury", "Earth", "Venus", "Mars", "Pluto", "Saturn"];
var [first, second, ...rest] = new Set(["Mercury", "Earth", ...planets, "Saturn"]);
console.log(first);
console.log(second);
console.log(rest);
Upvotes: 1