Destructuring: Array - 04

Example 1:

const alphabet = ["A", "B", "C", "D", "E", "F", "G"];
const number = [1, 2, 3, 4, 5, 6, 7];

const [a, b, c] = alphabet;

console.log(a);
// Result: A

console.log(b);
// Result: B

console.log(c);
// Result: C

Example 2:

If we wanna skip any of the elements of an array.

const alphabet = ["A", "B", "C", "D", "E", "F", "G"];
const number = [1, 2, 3, 4, 5, 6, 7];

const [a, , c] = alphabet;

console.log(a);
// Result: A

console.log(c);
// Result: C


Example 3:

If we wanna get the rest of the element, then we can do it with a spread operator(with three dots).

const alphabet = ["A", "B", "C", "D", "E", "F", "G"];
const number = [1, 2, 3, 4, 5, 6, 7];

const [a, , c, ...rest] = alphabet;

console.log(a);
// Result: A

console.log(c);
// Result: C

console.log(rest);
// Result:
// ["D", "E", "F", "G"];

Example 4:

If we wanna combine two arrays…

const alphabet = ["A", "B", "C", "D", "E", "F", "G"];
const number = [1, 2, 3, 4, 5, 6, 7];

const newArray = [...alphabet, ...number];

console.log(newArray);
// Result:
// ["A", "B", "C", "D", "E", "F", "G", 1, 2, 3, 4, 5, 6, 7];


Post a Comment

Previous Post Next Post