Array Destructuring
-
Decomposing a structure into individual parts
-
It is about assignment and not declaration for variables
-
Imperative Approach
const data = () => {
return [1,2,3];
}
const tmp = data();
const first = tmp[0]
const second = tmp[1]
const third = tmp[2]
const fourth = tmp[3] !== undefined ? tmp[3] = 4; // Default value
- Declarative Destructuring Equivalent Approach
const data = () => {
return [1,2,3,,5,6,7,8];
}
const [
first,
second,
third,
fourth = 10, //Default value
...arr //Spread/Gather Operator puts the rest into an array arr
] = data();
console.log(second) //2
console.log(fourth) //10
console.log(arr) // [5,6,7,8]
//If there are more variables than values from return then the extra variables would be undefined
//Default values would be used if the value is undefined
Spread Operator
- (...)
- Allows array or string to be expanded into different variables
const str = ["aaa","bbb","ccc"]
function test(x,y,z) { //...str elements assigns in order
console.log(x) //aaa
console.log(y) //bbb
console.log(z) //ccc
}
function test2(elements) { //Takes in array
console.log(...elements) //aaa bbb ccc
}
test(...str) //Give in 3 elements
test2(str) //Give in array
Comma Seperation
- When you use comma, you are not assigning those values. Using before a gather allows you to skip a few before gathering.
const data = () => {
return [1,2,3,4,5,6,7,8,9];
}
const [
first, //1
, //Commas just does not assign to anything
, //Skips 2 and 3
fourth, //4
,,,//Skips 5,6,7
...arr // [8,9]
] = data();
console.log(first) // 1
console.log(fourth)// 4
console.log(arr)// [8,9]
Extra. Swapping variables with Destruct
let x = 10;
let y = 50;
let z = 99;
let a = 1;
[x,y,z,a] = [a,z,y,x]
//x swaps with a, y swaps with z, ...
console.log(x) //1
console.log(y) //99
console.log(z) //50
console.log(a) //10
Parameter Arrays
- You can destruct arrays in the input parameters as well in a function
const data = ([
first,
second=20,
third
] = [9,,11]) =>{
console.log(first) //9
console.log(second) //20
console.log(third) //11
}
data() //Using defaults in data function
Nested Array Destructuring
const data = () => {
return [1,[2,[3]],4]
}
const [
first,
[
second,
[
third
]
],
fourth
] = data()
console.log(first);
console.log(second);
console.log(third);
console.log(fourth);
Array Methods
- findIndex and indexOf finds the index of the element and returns -1 if not found
- find Method
const arr = [{a:1},{a:2}]
console.log(arr.find(function match(v){
return v && v.a === 1
})); //{a:1}
- includes, checks to see if element is in the array
const arr = [1,2,3,5,6]
console.log(arr.includes(4)); //false
console.log(arr.includes(5)); //true
- flat and flatMap, flattens out nested arrays into a different nested array at the end
const nestedArr = [1,2,[3],[7,[4,5,6]]]
console.log(nestedArr); //[ 1, 2, [ 3 ], [ 7, [ 4, 5, 6 ] ] ]
console.log(nestedArr.flat(2)); //Flats by 2 levels of nesting
/**
[
1, 2, 3, 7,
4, 5, 6
]
*/