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

Show parent comments

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