Interview Question

Front End Engineer Interview

-

Meta

Given an array, return it's flattened structure(skip objects)

AnswerAdd Tags

Interview Answers

10 Answers

1

function flatten(input) { return (input || []).reduce(function (prev, current) { if (Array.isArray(current)) { return prev.concat(flatten(current)); } else { prev.push(current); return prev; } }, []); }

Dan on

1

function flattenRecursive( a, ret ) { return a.reduce((ret, cur) => { if (Array.isArray(cur)) { flattenRecursive(cur, ret); } else if(typeof cur !== 'object'){ ret.push(cur); } return ret; }, ret || []) } function flattenIterative( a ) { let ret = []; while( a.length ) { let cur = a.pop(); if (Array.isArray(cur)) { a = [...a, ...cur]; } else if ( typeof cur !== 'object' ){ ret.push(cur) } } return ret.reverse(); }

Marti on

0

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

Anonymous on

0

const flatten = (input = []) => input.reduce((agg, cur) => Array.isArray(cur) ? [...agg, ...flatten(cur)] : [...agg, cur], []);

Idan on

0

let flatten = arr => arr.flat()

Hakan Alpay on

0

Won't work in strict mode but comes close: var flatten = function(arr){ newArr = (typeof newArr === "undefined"? [] : newArr ); arr.forEach(function(elem,id,ar){ if( Array.isArray(elem)){ flatten3(elem); }else if( elem.constructor === Object ){ void 0; }else{ newArr.push(elem); } }); return newArr; }

Ryan on

0

function flattenArr(arr) { this.flatArr = this.flatArr || []; var i; for (i=0; i

Anonymous on

0

function flatten(arr) { arr = arr.filter(removeObjects); // remove the objects return arr.reduce(function (a, b) { return a.concat(b); }); function removeObjects (item) { // filter for arrays first if(Array.isArray(item)) { return true; } //filter for objects next else if (typeof item === 'object') { return false; } // return the rest return true; } }

Matt H on

0

function flatten(arr){ if(!arr.length){ return "No items in array"; } else{ var new_array = []; } for (var idx = 0; idx < arr.length; idx++) { if(typeof arr[idx] == "object"){ for(var item = 0; item < arr[idx].length; item++){ console.log(arr[idx][item]); new_array.push(arr[idx][item]); } } else{ new_array.push(arr[idx]); } } return new_array; }

Tiffany on

0

function ArrFlat(arr){ var retArr = []; arr.forEach(function(element){ if(Array.isArray(element)){ element.forEach(function(innerelem){ retArr.push(innerelem) }); } else if(typeof element === 'number'){ retArr.push(element); } }); return retArr; }

simple forEach structure on

Add Answers or Comments

To comment on this, Sign In or Sign Up.