xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

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 发布文章使用:只允许注册用户才可以访问!


posted @ 2020-09-12 11:30  xgqfrms  阅读(280)  评论(2编辑  收藏  举报