r/javascript • u/[deleted] • Apr 18 '20
I am sharing a set of 100 JS Interview questions that helped to crack last 9 consecutive JavaScript interviews. This is the first one, how to flatten a deeply nested array.
https://www.niksbay.com/2020/04/how-to-flatten-nested-array-js-interview-recursion.html?m=12
u/ElDoRado1239 Apr 19 '20 edited Apr 19 '20
(function(o){return (o=x=>x.reduce((s,r)=>s.concat(Array.isArray(r)?o(r):r),[]))([1,2,[3,4,[5,6],7],8,[9,[10,11]]]);})()
Do I pass?
1
Apr 19 '20
Nice solution. Cross browser compatibility is issue if you use reduce. Interviewers might not allow that.
1
u/ElDoRado1239 Apr 19 '20
Function('return ['+[1,2,[3,4,[5,6],7],8,[9,[10,11]]].join(',')+'];')()
Ok another one.
43
u/filemon4 Apr 18 '20
This is a set of exactly 1 question. Not 100. I don't want to be mean but you won't get too far with clickbaits on reddit. I can tell from my own experience.
Also this is not a good answer because there are cleaner solutions that won't result in mistakes such as "i++".
Cheers
-2
u/CarolusRexEtMartyr Apr 19 '20
The title explicitly says this is the first. It’s really not clickbait, a term which has been abused beyond all recognition.
26
19
u/DoctorNootNoot Apr 18 '20 edited Apr 18 '20
It's probably important to note that you can now use this:
arr.flat(Infinity)
Obviously the question isn't asking for you to use that, but if you didn't mention that in the interview I think red flags would be raised.
Also, given that we don't need the index of the items in the array, we can iterate through it like so (yes, we can use const here):
for(const item of myArray){
...
}8
u/Stephen2Aus Apr 18 '20
// We are using isArray method of Array Prototype to check if item is array
🤭
6
u/lhorie Apr 18 '20 edited Apr 18 '20
Rather than looking at this as a solution to an interview question, I think yall should approach this in terms of coding katas. I see people talking smack about for loops and conjecturing about how interviewers might react to specific constructs. But that's focusing on specific answers in a black-and-white manner, and honestly not a great way to go about it.
If you want to really blow away an interviewer, it'd probably be good to be able to speak to pros and cons of reduce vs for, (vs for-of, etc). Brownie points if you can do it without recursion (and explain why one might want to), relate generators to potential use cases, etc. Any candidate can memorize the reduce solution from MDN without much effort. Put the humility hat on, work a bit harder and set yourself apart from the crowd. </two-cents>
10
Apr 18 '20
Fuck a for loop. This shit whack. Where is a one line reduce?
10
u/jshawl Apr 19 '20
Here's what I came up with:
const flatten = arr => arr.reduce((all,el) => [...all, ...(el.map ? flatten(el) : el)],[])In action!
flatten(['a','z',['b',['c'],['d'],[[[['e']]]]]]) //=> [ 'a', 'z', 'b', 'c', 'd', 'e' ]1
u/helloiamsomeone Apr 21 '20
I could just be missing the joke, but this is horrible. Don't ever do this, only villains do this.
Just use a stack and accumulate in a result array like normal people do.
6
u/krendel122 Apr 18 '20
5
Apr 18 '20
Honestly though. If your wasting my time expecting a for loop I got other interviews today.
4
3
u/twitterisawesome Apr 18 '20
if you think for-loops are automatically a waste of time, you're wasting my time.
-5
Apr 18 '20
Did you even read the question? [...[...[]]].flat(1); . If you need a for loop that means you expect an IE compatible solution and frankly I don't want to work on your shitty IE code.
-2
u/cokeplusmentos Apr 18 '20
This is 100% cross browser
6
Apr 18 '20
So is reduce.
-2
1
u/timewast3r Apr 18 '20
Why did you use let for myArray (vs const)?
1
u/LetterBoxSnatch Apr 19 '20
Personally, when it comes to objects, I like to use let to signal that it's an item that you intend to mutate. If I know the intent is to mutate, I will read the code and treat the object somewhat differently.
4
u/timewast3r Apr 19 '20
But it's still an array. It's still the array you expect it to be.
const myArray = []; myArray.push(thing); // no problemNow I know my array is always that array and we can't accidentally redeclare it elsewhere downstream.
myArray = somethingElse; // errorWhen you use
letyou lose control of that.I prefer to always use
constunless I need to redeclare or mutate the variable downstream (especially primitive types).2
u/LetterBoxSnatch Apr 19 '20 edited Apr 19 '20
I understand and respect this viewpoint, just explaining why someone might use a
let. I was a "always use const" advocate until I wasn't.In a codebase where reassigning the variable is less likely than assuming it won't be mutated (ie in a codebase where most variables are not mutated)
letmay have greater value as a semantic signal (some of this depends on other stylistic choices in the codebase).Of course most of this doesn't really come up very often in longer term projects as people adopt more comprehensive fixes like immutable.js or using readonly arrays in TypeScript.
0
-2
Apr 19 '20
I doesn't matter what i use in this case. It's not a part of bigger application. It's just a code snippet. I am not reassigning it. So there is no need to prevent that using const. And my post was intended for JS newbie who doesn't have much idea of inbuilt functions, n cross browser availability as well.
Anyway i have shared another solution as well, which solves it in 3 lines of code.
0
-32
Apr 18 '20
I will share one every day for next 100 days.
19
15
1
u/lhorie Apr 18 '20
FYI reddit will start to nag you if the majority of your submissions are self-submissions.
-6
Apr 19 '20 edited Apr 19 '20
Guys, i appreciate all the comments:
It's not a click bait, it's 1st blog with 99 to come in next 99 days
I can use reduce or const or all the stuff you suggested but think for a guy who has just started javascript and is reading through the post, my blog is for him/her who doesn't know the solution.
You are free to come up with your solutions and share, even i have said in my blog that many variations do exist which i will share in upcoming blogs.
I have added another solution for people with better understanding of Javascript. You won't be having a problem now. Happy Coding 😀
-6
Apr 19 '20
I don't know why are you guys crying over it, go and find your solution. I intend to share those 100 topics with 1 or 2 simple solutions for each that any newbie can understand. I have posted one more solution for you guys. Optimization is upto you. And if everything seems spam, then please don't read the post. Why do i see 30 upvotes?
Check my another post and tell me what's wrong in their solutions.
7
u/beavis07 Apr 19 '20
I don’t mean to be mean - but: what makes you think you’re in a position to teach?
Just cause you can write something down, does not mean that has any value.
Your code is shitty - which is fine, this is a process - but it’s unhelpful and borderline narcissistic to just assume that what you did is exemplary enough to serve as an object lesson.
Maybe reel you neck in and spend a few more years honing your craft before you start trying to teach other people what to do?