r/javascript • • Mar 02 '19

Useful javascript one-liners.

https://medium.com/@smellycode/js-one-liners-8bc0a6af2345?source=friends_link&sk=a9295a05aef9e514e137fca7eeb89cd1
344 Upvotes

96 comments sorted by

View all comments

-7

u/98ea6e4f216f2fb Mar 02 '19

This is not a one-liner. Also it's very un-idiomatic javascript. If you're going to line break, then use a curly brace.

5

u/smellycode Mar 02 '19

98ea6e4f216f2fb

You are right. This is not a one-liners. I added it to complete the `flatten` with any level. Prolly I should add one line which tells it's not one liner.

Adding curly braces to line break is personal preference. :)

8

u/ShortSynapse Mar 02 '19

It should be noted that we now have the native Array#flat() method.

[[1,2],[3,[4,5]]].flat(Infinity) // [1,2,3,4,5]

1

u/[deleted] Mar 02 '19

Ah I had no idea about passing an argument to it, and Infinity is very clever, thanks for this.

1

u/haykam821 Mar 02 '19

Infinity is too clever. Try this instead:

const flatInfinity = arr => {
	while (true) {
		if (arr.some(item => Array.isArray(item))) {
			arr.forEach((item, index) => {
				if (Array.isArray(item)) {
					arr.splice(index, 1, ...item);
                }
            });
		} else {
			return arr;
		}
    }
}

1

u/ShortSynapse Mar 05 '19

Why is Infinity too clever? And how is mutating the array in place within a while(true) better?

You should use the native Array#flat method. Pass it the depth that you want to recurse to. Whether that's Infinity to flatten everything, Number.MAX_VALUE for the same thing but using an actual number, or an arbitrary depth if desirable.

1

u/haykam821 Mar 05 '19

I’m kidding