js array flat all in one
js array flat all in one
array flat

flatMap
flatMap > flat + map
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap
var new_array = arr.flatMap(function callback(currentValue[, index[, array]]) {
// return element for new_array
}[, thisArg])
flat
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
var newArray = arr.flat([depth]);
// depth defaults 1
// The depth level specifying how deep a nested array structure should be flattened.
map
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
reduce
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
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
https://www.npmjs.com/package/lodash.flatten
https://www.npmjs.com/package/lodash.flattendeep
https://www.npmjs.com/package/lodash.flattendepth
https://lodash.com/docs/4.17.15#flatten
_.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)

refs

https://stackoverflow.com/questions/10865025/merge-flatten-an-array-of-arrays
https://flaviocopes.com/javascript-flatten-array/
https://linguinecode.com/post/new-es2019-javascript-features
https://github.com/lgwebdream/FE-Interview/issues/8
https://atendesigngroup.com/articles/array-map-filter-and-reduce-js
https://www.samanthaming.com/tidbits/71-how-to-flatten-array-using-array-flat/
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/13656379.html
未经授权禁止转载,违者必究!

浙公网安备 33010602011771号