js array flat all in one array flat Array.flatAll
array flat
flatMap
flatMap > flat + map
var new_array = arr.flatMap(function callback(currentValue[, index[, array]]) {
// return element for new_array
}[, thisArg])
flat
var newArray = arr.flat([depth]);
// depth defaults 1
// The depth level specifying how deep a nested array structure should be flattened.
Array.flatAll
// prototype
demos
['My dog', 'is awesome'].map(words => words.split(' '))
//[ [ 'My', 'dog' ], [ 'is', 'awesome' ] ]
['My dog', 'is awesome'].flatMap(words => words.split(' '))
//[ 'My', 'dog', 'is', 'awesome' ]
const log = console.log;
const nested = [['????', '????'], ['????']];
const flattened = nested.flat(nested.length);
log(flattened);
// ['????', '????', '????']
const arr1 = [1, 2, 3, [1, 2, 3, 4, [2, 3, 4]]];
function flattenDeep(arr) {
return arr.reduce(
(acc, val) =>
Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val),
[],
);
}
flattenDeep(arr1);
// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
lodash
lodash.flatten
lodash.flattendeep
lodash.flattendepth
_.flatten([1, [2, [3, [4]], 5]]);
// => [1, 2, [3, [4]], 5]
_.flattenDeep([1, [2, [3, [4]], 5]]);
// => [1, 2, 3, 4, 5]
const arr = [1, [2, [3, [4]], 5]];
_.flattenDepth(arr, 1);
// => [1, 2, [3, [4]], 5]
_.flattenDepth(arr, 2);
// => [1, 2, 3, [4], 5]
nested array to object
Object.fromEntries()
const log = console.log;
const arr = [
["a", 1],
["b", true],
["c", []],
["d", {}],
["e", "????nested array to object"],
];
const obj = Object.fromEntries(arr);;
log(obj)