Photo by Ilya Pavlov on Unsplash
Array Methods — flat(), flatMap(), reduceRight(), copyWithin(), from()
Today I will discuss about the new methods of Javascript ES2018. Some of the methods I will be discussing about are
- flat()
- flatMap()
- reduceRight()
- copyWithin()
- from()
The flat()
method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
// 1. flat()
const matrix1 = [[1,2,3], [4,5,6]];
let flatArray = matrix1.flat(1);
console.log('flatArray', flatArray); // flatArray [1, 2, 3, 4, 5, 6]
We can use flat(Infinity)
to flatten the array into a single level.
const matrix2 = [[1,2,3], [4,5,6], [1], [[1], [[[1]]]]];
let flatArrayInfinity = matrix2.flat(Infinity);
console.log('flatArrayInfinity', flatArrayInfinity);
// flatArrayInfinity [1, 2, 3, 4, 5, 6, 1, 1, 1]
let total = matrix2.flat(Infinity).reduce((a, v) => a + v, 0);
console.log('total', total); // total 24
The flatMap()
method first maps each element using a mapping function, then flattens the result into a new array. I
It is identical to a map()
followed by a flat()
of depth 1, but flatMap()
is often quite useful, as merging both into one method is slightly more efficient.
// 2. flatMap()
const nums = [1, 2, 3];
const str = ["one", "two", "three"];
let mapped = nums.map((value, i) => [value, str[i]]);
let flatMapped = nums.flatMap((value, i) => [value, str[i]]);
console.log('mapped', mapped);
// mapped [1, "one"], [2, "two"], [3, "three"]
console.log('flatMapped', flatMapped);
// flatMapped [1, "one", 2, "two", 3, "three"]
The reduceRight()
method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value.
// 3. reduceRight()
const strs = ['t', 's', 'e', 'b'];
let tseb = strs.reduce((c, v) => c + v);
console.log('tseb', tseb); // tseb tseb
let best = strs.reduceRight((c, v) => c + v);
console.log('best', best); // best best
The copyWithin()
method shallow copies part of an array to another location in the same array and returns it without modifying its length.
// 4. copyWithin()
const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
array.copyWithin(8); // takes the (n-1)th index of the array, then copies the entire array again.
console.log(array); // [0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3]
The Array.from()
method creates a new, shallow-copied Array
instance from an array-like or iterable object.
// 5. from()
const name1 = "amrit"
console.log(Array.from(name1)); // ["a", "m", "r", "i", "t"]
const name2 = new Map([[1, 2], [2, 4], [4, 8]]);
console.log(Array.from(name2)); // [[1, 2], [2, 4], [4, 8]]
const name3 = new Map([['1', 'a'], ['2', 'b']]);
console.log(Array.from(name3.values()));// ['a', 'b'];
console.log(Array.from(name3.keys()));// ['1', '2'];
Thanks for reading.