Pergunta de entrevista da empresa Meta

Can you write a function that deeply flattens an array?

Respostas da entrevista

Sigiloso

15 de jan. de 2017

Depending on how the non-arrays must be handled, this function does the job if you can just return the argument when it's not an array: function flatten(array) { if (!Array.isArray(array)) { return array; } return array.reduce((acc, cur) => { return acc.concat(flatten(cur)); }, []); }

3

Sigiloso

9 de ago. de 2017

function flatten (arr) { return arr.reduce(function (res, elem) { if (elem instanceof Array) { return res.concat(flatten(elem)) } else { res.push(elem) return res; } }, []) }

1

Sigiloso

25 de jan. de 2018

let flat = (z = []) => { return !Array.isArray(z) ? [].concat(z) : (z.length > 0) ? flat(z.splice(0, 1)[0]).concat(flat(z)) : z }

Sigiloso

9 de jul. de 2018

const flatten = (arr) => String(arr).split(','); Handles deeply nested arrays, but will convert all values to string.