r/javascript • • Mar 18 '19

What's your favorite, most useful javascript one-liner?

385 Upvotes

422 comments sorted by

8

u/Linux_is_awesome Mar 18 '19

personal favorite: var item = items[Math.floor(Math.random()*items.length)];

It randomly selects an element from an array.

4

u/[deleted] Mar 19 '19

I like it. A similar requirement, but you can't pull the same item twice:

const shuffled = items.slice().sort(() => 2*(Math.random() - 0.5));
const item = shuffled.pop();

2

u/barrtender Mar 19 '19 edited Mar 19 '19

This does not make a uniform distribution for all (any?) sizes of arrays. I ran into an issue with one version of v8 where this consistently made an array of 1-10 reversed. I'm on my phone but if I remember tomorrow I should write something up about this

Edit - I put some more info below about the distribution. https://www.reddit.com/r/javascript/comments/b2o6f2/whats_your_favorite_most_useful_javascript/eiwrgp9/

→ More replies (7)
→ More replies (1)

339

u/Drugba Mar 19 '19

Saw this one on here just a few weeks ago.

[... new Set(arr)]

Basically a super short way to remove any duplicates from an array of primitives.

17

u/[deleted] Mar 19 '19

Is order guaranteed to be maintained with the Set data structure here?

26

u/Drugba Mar 19 '19 edited Mar 19 '19

No, it's not.

/u/BTOdell is correct. Insertion order is preserved when you spread a set.

26

u/BTOdell Mar 19 '19

The Set object in JavaScript preserves insertion order. So if you create a Set from an array, it will preserve the order when you spread it back out (but without duplicates).

9

u/Drugba Mar 19 '19

Oh, wow. You are totally correct.

I was under the impression that, because sets (the data structure) do not have an order, you wouldn't be able to guarantee order when you spread it, but that to totally wrong.

7

u/NoInkling Mar 19 '19

Worth noting that if there were duplicates in the original array, the position for an element will be based on its first occurrence.

> Array.from(new Set([1,'foo',2,'foo']))
[1, "foo", 2]

13

u/[deleted] Mar 19 '19

[...new Set(arr.map(x => JSON.stringify(x))].map(x => JSON.parse(x))

Same thing, but with arrays of objects. Apparently probably deterministic but maybe not it depends ohgodhelpme

18

u/cheekysauce Mar 19 '19

It'll barf on circular references unfortunately.

41

u/dodeca_negative Mar 19 '19

Don't we all

3

u/NoInkling Mar 19 '19 edited Mar 19 '19

It will have issues with anything non-serializable, explicitly set undefineds will disappear on objects (if that matters), and undefined inside arrays will turn into null. And maybe some other edge cases I'm forgetting.

4

u/SoInsightful Mar 19 '19

It will implode on undefined, circular references, and most appallingly, objects with different key orders. Not really obscure edge cases. People really need to stop using the JSON trick.

2

u/noruthwhatsoever Mar 19 '19

I like this one, very clever

→ More replies (2)

3

u/oorza Mar 19 '19

Copying your entire data structure twice to remove duplicates is good to you?

5

u/Drugba Mar 19 '19 edited Mar 20 '19

It depends. If I've got a list of 10 items, this is totally fine. Sure it's I'm using more space than I need, but it's pretty negligible and as long as it's not in the global context, the memory is going to be released soon enough anyway. If I've got a list of two million items, of course this is stupid.

One liners often trade performance for terseness, which is what this does. The question asked wasn't "Write the most performant code you can", it was "what is your favorite one liner" and that's what this is.

If you're writing JS code where literally every single byte counts, more power to you, but most people aren't. This is perfectly acceptable for small arrays.

→ More replies (2)

2

u/noruthwhatsoever Mar 19 '19

I like this one a lot, I use it regularly

→ More replies (6)

114

u/EllisLloyd Mar 19 '19 edited Mar 19 '19

This:

const sleep = (ms) => (new Promise(resolve => setTimeout(resolve, ms)));

It's the JS version of the sleep command that I so miss from a lot of languages like Python and BASIC. The new async/await syntax allows you to call this function with a simple await sleep(2000); wherever you feel like it. Incredibly useful for games, animations and every time you need a timeout.

15

u/higherpublic Mar 19 '19

const sleep = (data, ms) => (new Promise(resolve => setTimeout(()=> resolve(data), ms)));

For sleeping between then()’s and passing data between after the sleep

25

u/FormerGameDev Mar 19 '19

Make Ms the first param

22

u/dougalg Mar 19 '19

If we're going there, why not:

const sleep = (ms) => (data) => new Promise(resolve => setTimeout(()=> resolve(data), ms));

Which gives you a nice thing like:

makeApiCall().then(sleep(1000)).then(processData)

19

u/tjoskar Mar 19 '19

If we're going there, why not:

const sleep = ms => data => new Promise(resolve => setTimeout(resolve, ms, data))

😉

→ More replies (2)

4

u/GBcrazy Mar 19 '19

A synchronous blocking sleep variation:

const sleep = ms => { 
    const desired = Date.now() + ms; 
    while(Date.now() < desired) {}
};
→ More replies (3)

1

u/reyhanahmed Mar 25 '19

Why wrap it in a promise? setTimeout should work.

3

u/EllisLloyd Mar 25 '19

Because when you use await on it it looks like synchronous code. How are you going to use setTimeout in purely imperative code without screwing up your flow?

→ More replies (3)
→ More replies (1)

95

u/tbicknell3 Mar 19 '19

debugger;

14

u/thisguyfightsyourmom Mar 19 '19

Even with all the cool tools in the chrome inspector, dropping a debugger in the source is so quick, easy, and effective

I’m always a little embarrassed when I start typing them while pairing though

2

u/Hanlonsrazorburns Mar 19 '19

I wrote a little piece using environment variables that turns debugger on locally as well as different levels of logging in my code. It's been very helpful.

2

u/snifty Mar 19 '19

Debugging is embarrassing?

→ More replies (5)

4

u/IntelligenceOptional Mar 19 '19

Just make sure your linter reminds you to dedebugger...

→ More replies (3)

2

u/TwiNighty Mar 19 '19

I used to use it all the time. Now I only use it when I have no sourcemaps (which is very rare). Other times I just add a breakpoint, which is way easier to manage.

150

u/Loves_Poetry Mar 18 '19
array.every(Number.isFinite)

Because it's plain english.

46

u/dmethvin Mar 19 '19

Also very poetic, so I can see why you like it.

19

u/ahartzog Mar 19 '19

TIL about array.every. Awesome tool, thanks!

11

u/Satoshi_Hodler Mar 19 '19

There's a small caveat that it always returns true on empty arrays, which might be not what you need.

27

u/Tysonzero Mar 19 '19

That's the mathematically correct thing to do, it's actually a pretty fundamental mathematical principle. Vacuous truth

→ More replies (2)

7

u/NoInkling Mar 19 '19 edited Mar 19 '19

If it's not, you can do:

array.length && array.every(Number.isFinite)

// If it must evaluate to a boolean:
!!array.length && array.every(Number.isFinite)
// or
array.length > 0 && array.every(Number.isFinite)
→ More replies (2)

8

u/Tysonzero Mar 19 '19

You'd love Haskell:

all (> 5) array
-- all (> 5) [4, 5, 6]
-- False

for array print
-- for [1, 2, 3] print
-- 1
-- 2
-- 3

takeWhile (any (< 3)) arrayOfArrays
-- takeWhile (any (< 3)) [[1, 2], [3, 4], [2, 3]]
-- [[1, 2]]
→ More replies (2)

101

u/nqvst Mar 18 '19

items[n % items.length]

gets an item from the list and wraps around to the start if n is larger than the list

2

u/jseego Mar 19 '19

Awesome

2

u/pookage Senior Front-End Mar 19 '19

This is so simple and delicious...

1

u/pslatt Mar 19 '19

I see things like this and I just feel so stupid at the code I would have wrote to do the same thing. But if I *keep* seeing things like this, maybe I'll be clever too one day.

→ More replies (34)

28

u/malinkie Mar 19 '19

// @TODO

7

u/jamesaw22 Mar 19 '19

// HACK

3

u/[deleted] Mar 19 '19

This is not what I meant when I wanted to become a hacker as a kid.

→ More replies (3)

6

u/RecklessGeek Mar 19 '19

Why the @?

5

u/lordxeon Mar 19 '19

Some IDEs have syntax highlighting for @TODO

51

u/farelikoyunkavalcisi Mar 18 '19

I think array functions like map/filter/reduce.

130

u/Earhacker Mar 18 '19 edited Mar 19 '19

Not exactly a one-liner, but my neatest quick trick: If you have a one-liner arrow function, but you want to log out the parameter, you don't need to give it curly braces and an explicit return.

Go from this:

const addFortyTwo = number => number + 42

To this:

const addFortyTwo = number => console.log(number) || number + 42

It works because console.log returns undefined, which is falsey, so the expression evaluates to the other side of the || 'or' operator, but only after running the console.log. Neat!

41

u/seiyria Mar 19 '19

You could also use the , operator for this, like so:

const add42 = n => (console.log(n), number + 42);

Although, since you need parens around it, it's a bit more obnoxious.

14

u/natziel Mar 19 '19

This is especially handy with React. Imagine you have a component like the one below, but you want to log the props

const Example = (props) => (
  <Foo ...props />
)

Dead easy to add or remove the log without having to mess with the implementation of the component

→ More replies (2)
→ More replies (6)

8

u/msluther Mar 19 '19

I use this all the time but as a condition on a breakpoint. Because it’s falsey, it won’t stop at the breakpoint, but you get console log statements without altering the code. Super handy for dealing with more time sensitive code or where it’s too much work to alter the source.

5

u/[deleted] Mar 19 '19

Oh my goodness why have I never thought of this? Thank you for saving me 2 seconds times a billion

3

u/Dextro_PT Mar 19 '19

Due to the same fact, if you want to log a variable at any given point, you can just add a conditional breakpoint with console.log(variable) and it'll log without stopping execution

2

u/ScientificBeastMode strongly typed comments Mar 19 '19

Oh wow this is brilliant!

2

u/joopez1 Mar 19 '19

thank you for this

2

u/jseego Mar 19 '19

That is cool

1

u/evenisto Mar 19 '19

Holy shit, done are the days of adding curly braces just to log shit. Thank you so much.

1

u/bethegood Mar 19 '19

This one wins for me. Thank you!

→ More replies (1)

42

u/[deleted] Mar 19 '19

If you have a bunch of variables a, b, c, d, e:

console.log({ a, b, c, d, e }) to quickly log all of them as key-val pairs.

Spread operator for bypassing array methods that mutate:

const sortedArr = [...originalArr].sort()

26

u/SuperFLEB Mar 19 '19

It's useful if you only have one variable, too.

console.log({myvar})

to get the name along with the value, instead of

console.log('myvar is', myvar);

5

u/duGarbandier Mar 19 '19

My lord almighty

2

u/fgutz Mar 19 '19

oh god this is so obvious now that I feel stupid for not doing this lol

4

u/spatmonkey Mar 19 '19

I do the first one all the time, and I'll definitely be using the second one from now on.

9

u/[deleted] Mar 19 '19

Just a heads up: spread operators are generally not super quick. If you are dealing with large arrays, you may not want to do this. As with everything in software engineering, it is probably best to play it by ear ;)

8

u/[deleted] Mar 19 '19

Array.prototype.slice is a bit faster (~25%) but the spread syntax is a bit cleaner when speed doesn't matter imo. It also allows you to stick elements into your array clone really quickly and cleanly:

const leaderboard = [...highScores, userScore].sort()

5

u/[deleted] Mar 19 '19

Aw hell yea I use spread all the time. Object and array. Just wanting to spread the word about its slowness. Not an issue for probably 99% of use cases but ya never know. This is the internet after all. Also I really like your example of array spread syntax making things easy to understand!

2

u/theQuandary Mar 19 '19

You can also use console.table() instead of log for improved readability.

19

u/drboyfriend Mar 19 '19

console.table(obj1); and console.log(JSON.stringify(obj1, null, 2); for debugging.

3

u/thisguyfightsyourmom Mar 19 '19

I use console.log(JSON.stringify(yo, null, 2) when I need to copy paste objects out of the console—super quick way to get a pile of placeholder data

14

u/Oririner Mar 19 '19

just copy(yo) ;)

(in Chrome DevTools)

→ More replies (3)

76

u/anlumo Mar 18 '19

EU citizen here. Whenever a site presents me with a tracking consent form that has >500 checkboxes to click in order to tell them to disable all tracking, I open up the dev console and do something like this:

document.querySelectorAll('.whateverClassTheCheckboxHas').forEach(cb => cb.click());

6

u/BluudLust Mar 19 '19

Check out the extension "I do not care about cookies"

6

u/anlumo Mar 19 '19

If I'm reading the description correctly, that extension doesn't actually turn off the cookies, it just hides the popup.

→ More replies (2)

2

u/[deleted] Mar 19 '19

NodeLists do not have the Array functions on their prototype.

[].forEach.call(document.querySelectorAll('.whateverClassTheCheckboxHas'), cb => cb.click());

33

u/AwesomeInPerson Mar 19 '19

NodeList actually implements forEach(), with decent browser support. :)

12

u/anlumo Mar 19 '19

Hmm map doesn't work here in Chrome, but forEach does.

17

u/[deleted] Mar 19 '19

Oh, hey. Looks like forEach has been added to the WebIDL spec for NodeList and other DOM iterables. Ain't that fancy. Time to go revise a whole bunch of code!

11

u/the_argus Mar 19 '19

Can also use Array.from(document...).forEach(...)

13

u/BabyLegsDeadpool Mar 19 '19

Or just do [...document.querySelectorAll(...)].forEach(...)

8

u/Sn34kyMofo Mar 19 '19

Or, if you're in Chrome, use $$(), which is a console method that returns the result of querySelectorAll() as an array instead of a nodelist! Very succinct and handy when futzing with the DOM in DevTools.

Example: $$('.some-class').forEach(...);

→ More replies (2)
→ More replies (3)

0

u/[deleted] Mar 19 '19

[deleted]

→ More replies (3)
→ More replies (5)

15

u/redmoss6 Mar 18 '19

'#'+Math.floor(Math.random()*16777215).toString(16) for random hex color.

37

u/senocular Mar 18 '19

Will create invalid hex values for any random 0xFFFFF and below. Make sure to pad

'#' + Math.floor(Math.random() * 0xFFFFFF).toString(16).padStart(6, '0')

2

u/[deleted] Mar 20 '19

Can’t you also use 3 digit hex for some colors?

→ More replies (1)

5

u/[deleted] Mar 19 '19

I use a similar one-liner for making random IDs:

` _${Math.random().toString(36).substr(2)}`

> '_elkxwdnwg1s'

The leading _ is because the base36 number can still start with 0..9, and that's not valid for something like a variable name or HTML ID. The substr(2) is to get rid of the leading 0..

1

u/SuperFLEB Mar 19 '19

Anyone got anything for generating a random string of letters? I know you can use someNumber.toString(36) to get a string of letters and numbers, but I don't know how to get only letters.

3

u/inu-no-policemen Mar 19 '19
> String.fromCharCode(...Array.from({length: 12}, _ => Math.random() * 25 + 97 | 0))
"niapavvsjdfb"
→ More replies (1)

1

u/BunsOfAluminum Mar 19 '19

`'#' + Math.random().toString(16).substr(2,6)

40

u/a_dev_has_no_name Mar 19 '19 edited Mar 20 '19

~~anyNumber

Very short Bitwise operation to do rounding similar to the equivalent of Math.floor() i.e ~~5.9 // 5

It's handy for code golf or for angering coworkers

Edit: I didn't quite literally mean it's exactly the same as Math.floor I should've clarified on that. Also, I'm not suggesting anyone use this in production code, like I said it's nice for code golf.

28

u/anakappa Mar 19 '19

This is why we can't have nice things.

10

u/a_dev_has_no_name Mar 19 '19

Wait until you see the other tricks ಠ‿ಠ

14

u/thisguyfightsyourmom Mar 19 '19

Are you the guy who wrote the code I’m maintaining?

I hate you if so

14

u/rcfox Mar 19 '19

It's not the equivalent of Math.floor(). Math.floor() rounds towards negative infinity while integer truncation rounds towards zero.

> -2.3|0
-2
> Math.floor(-2.3)
-3

9

u/eGust Mar 19 '19

Bitwise operators will convert Number which is 64-bit precision IEEE-754 to 32-bit signed integer. So you will lose precision if your number is over 2**32, and will get -ve value if your number is between 2**31 and 2**32. I think that's why Airbnb eslint rules forbidden bitwise operators.

→ More replies (2)

6

u/Skhmt Mar 19 '19

asm.js uses anyNumber|0 to do the same thing

2

u/a_dev_has_no_name Mar 19 '19

Yeah, there are a few ways to do it. I was using num >> 0 before but ~~n is more concise and makes a little more sense (imo) like doing a double negation !!

→ More replies (1)

5

u/HideousNomo Mar 19 '19

I've been using num | 0 for this very thing

→ More replies (1)
→ More replies (1)

8

u/[deleted] Mar 19 '19

console.log(“What’s a pretty little literal like you doing in a function like this?”)

15

u/grantrules Mar 19 '19
[...String.raw({ raw: ['',...Array.from( new Array(16), () => 'x'-'y')]}, '!namtaB ')].reverse().join("")

11

u/[deleted] Mar 19 '19

Holy type abuse!

6

u/Lesale-Ika Mar 19 '19

"NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN Batman!"

7

u/action_jackosn Mar 19 '19

Array.from({length: 5}, (v, i) => i); := [0, 1, 2, 3, 4]

13

u/Darren1337 Mar 19 '19

I'm about to end this man's whole career.

[...Array(5).keys()]

2

u/NoInkling Mar 19 '19

I can't think of a use case where I'd want to materialize an array of numbers equivalent to their index - I'd just use the map function directly.

→ More replies (2)

18

u/ReaderSeventy2 Mar 18 '19

console.log(foo);

35

u/senocular Mar 18 '19

Haven't you heard? You don't need JavaScript for that anymore ;)

https://www.youtube.com/watch?v=uddZX9ZK6wY&t=31

6

u/ReaderSeventy2 Mar 18 '19

I had not. Thanks.

8

u/KinkyCode Mar 19 '19

That seems awfuly cumbersome when you may as well just log stuff as you build it...

→ More replies (3)
→ More replies (4)

5

u/kommentz Mar 19 '19

I like this a lot because it uses time itself for the animation.

let currentDate = new Date();
hero.y = 100 + (Math.cos(currentDate.getTime() * 0.002) * 25);

1

u/[deleted] Apr 02 '19

[removed] — view removed comment

2

u/kommentz Apr 03 '19

I cheated. This was a snippet of ActionScript 3, oscillating an object on its Y axis but it would work in Canvas (pretty much) so I showed it.

5

u/Thlemaus Mar 19 '19

Adding attr/val to an object if condition is true

{

...(YOUR_CONDITION && { OBJ_KEY: OBJ_VAL })

}

1

u/wthit56 Mar 20 '19

What is that adding it to? Would it not just create an object within that conditional?

→ More replies (4)

5

u/Dmitry_Olyenyov Mar 19 '19

setTimeout(()=>{debugger},5000) To keep dropdowns opened, menu hovered and so on. All things that disappear after losing focus

5

u/kichien Mar 19 '19

Chrome dev tools - select element, right click on the element in the inspector, select "Break on" > "subtree modifications". Then you can click on the element and see it's focused state attributes in the inspector.

→ More replies (2)

5

u/Morklympious Mar 19 '19

const clamp = (number, min, max) => Math.min(max, Math.max(number, min))

It’s a good clamp for when you need a number x to stay within the bounds of min and max!

4

u/lbs9000 Mar 19 '19

Console.log.....a life saver

4

u/GBcrazy Mar 19 '19 edited Mar 19 '19

I saw this some time ago and I found it clever as hell (even a bit hard to understand at first):

addressParts.map(Function.prototype.call, String.prototype.trim);

The trick is that map accepts a second argument, which is going to be the this context.

In short it does the same as:

addressParts.map(x => x.trim());

But you don't create a new object (a function in this case) !!!. Yeah, probably not a valid reason to do that shit in some code, but there is merit to it, it is clever.

Just to understand:

When you pass your callback to map, it gets called like this:

callback.call(thisArg, value)

But generally we never pass the third argument (thisArg), so what matters to us is callback(value). That said, we can abuse this. Let's make the substitutions for this scenario:

Function.prototype.call.call(String.prototype.trim, value)

Notice the double call? That's the magic right there. The call functions executes other function with a different context (this). Now, the double call makes we create the String.prototype.trim be the context of the first Function.prototype.call...Which means we are doing: String.prototype.trim.call(value)

Full and better explanation here

→ More replies (1)

3

u/robolab-io Mar 19 '19

Eh not that great but (new Date().getTime()) is my quick way to get Unix time in one line

8

u/GBcrazy Mar 19 '19

You can do this with Date.now()

→ More replies (1)
→ More replies (1)

3

u/wthit56 Mar 19 '19

(((n % 360) + 360) % 360)

Wraps all values to within 0 - 360 (pattern can be applied to any range).

1

u/420-jesus Mar 19 '19
(((n % 360) + 360) % 360)
=== (n % 360 % 360 + 360 % 360) % 360
=== (n % 360 % 360 + 0) % 360
=== n % 360 % 360 % 360
=== n % 360 

2

u/wthit56 Mar 19 '19

I don’t think that work for negative numbers, and negative numbers lower than -360.

→ More replies (1)

3

u/Sn34kyMofo Mar 19 '19

Two of my favorite Chrome console commands:

debug(funcName());

That sets a breakpoint on a function of interest.

$$('.ad-container').slice(-1)[0].remove();

The $$ mnemonic in DevTools is equivalent to querySelectorAll, except it returns the nodelist as an array, thus quickly and easily making array methods available. The above line removes the last result in the set from the document.

3

u/wanderer06 Mar 19 '19

Max and min numbers in an array:

Math.max(...foo);  
Math.min(...foo);

3

u/LouveredTang Mar 19 '19

I recently found "console. table()" and now I'm using it almost every day.

9

u/geoffgiller8 Mar 18 '19

I love this when using react: this.setState({ toggle: !toggle });

34

u/snorkl-the-dolphine Mar 18 '19

This can cause issues of it runs twice in quick succession. The safe way to do this is:

this.setState(({toggle}) => {toggle:!toggle});

16

u/[deleted] Mar 19 '19

this && setState? What is this, 2018? 😄

→ More replies (4)

2

u/NoInkling Mar 19 '19

Careful with syntax! You need a set of parens around the object:

this.setState(({toggle}) => ({toggle: !toggle}))

Even worse, your version won't throw a syntax error because toggle: is interpreted as a label, making it a pretty insidious bug (React should hopefully catch it though).

→ More replies (2)

3

u/robolab-io Mar 19 '19

Man, you'd love Vue...

2

u/dmethvin Mar 19 '19

The URLSearchParams object is cool I suppose, but I still have to support IE11 and usually I can get away with a one-liner to grab simple settings off the query string, like this:

var debugLevel = +(/\bdebugLevel=(\d+)\b/.exec(window.location.search)||[])[1] || 0;

2

u/ovpv Mar 19 '19

const obj = { foo: "john", bar : "doe"};

const {foo,bar} = obj;

→ More replies (3)

2

u/TheAceOfHearts Mar 19 '19

Sometimes I wanna quickly grab a list of links in a site:

copy([...document.querySelectorAll('a.class')].map(a => a.href).join('\n'))

2

u/wherinkelly Mar 19 '19

Console.info

2

u/[deleted] Mar 19 '19

Array.includes("my text")

2

u/malinkie Mar 19 '19

await new Promise(r =>setTimeout(r, 1000));

Single line sleep whenever you need it

2

u/knyg Mar 19 '19

someCondition && doSomething();

name === "Bob" && console.log(`Hi ${name}`);

short if/else statement

2

u/e13e7 Mar 19 '19

Not usually one lined, but short and useful nonetheless

const splitBy = (fn, arr) => arr.reduce(
  ([ l, r ], c) => fn(c)
    ? [ l.concat(c), r ]
    : [ l, r.concat(c) ],
  [[],[]]
)

// eg
const [ odd, even ] = splitBy(
  (x) => x % 2,
  [ 1, 2, 3, 4, 5 ]
)
→ More replies (1)

2

u/JohnyTex Mar 19 '19

You can do some funky stuff with logical operators, like:

Default values:

val = val || 42; // Set "val" to 42 if it's non-truthy
(Note that there's syntactic support for default parameter values in modern JS versions)

Null checks:
myObj && myObj.myMethod(); // Call myMethod only if myObj is truthy

2

u/[deleted] Mar 19 '19

debugger;

→ More replies (1)

2

u/Danieliverant Mar 19 '19

I've already commented that on some previous post like that, and it's not exactly one-liner but the "Group By" implementation:

var groupBy = function(xs, key) {
  return xs.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};

and using ES6 syntax:

const groupBy = (xs, key) => 
   xs.reduce((rv, x) = > {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});

and if you really want a one-liner I think that should work: (not tested!)

const groupBy = (xs, key) => xs.reduce((rv, x) => (rv[x[key]] = rv[x[key]] || []).push(x) || rv , {});

2

u/420-jesus Mar 19 '19

break outerLoop;

2

u/[deleted] Mar 19 '19

collection.map(x => x.someProp): Good way to list out properties of a collection

Array.map(Number): Sometimes I get IDs as string, quick way to convert them

3

u/TheScapeQuest Mar 19 '19

Discouraged by a lot of linters, but:

!!~[1,2,3].indexOf(2); // true

Polyfill for Array.prototype.includes()

→ More replies (3)

3

u/ChronSyn Mar 18 '19

I've been jumping all over self-invoking functions to assign values lately. It's been especially useful for one project which required checking existence of several different values while processing a render output, and where not creating values unless conditions pass, or in switch statements, is critical to the end result.

I came up with this fun little fetch 1-liner which uses self-invocation (untested, but it should work as I expect);

const data = (async () => await (await fetch('http://someurl.com/')).json().catch(e => console.log(e)))();

It's ideal for react-native, but any fetch-api implementation could use it. If the fetch call succeeds and the response can be turned into JSON, then data will be the contents of the response. If there's an error, that'll be console.logged, but the value of data will be undefined.

17

u/Peechez Mar 18 '19

I'm pretty sure if I tried to commit that I'd get slapped

→ More replies (4)

3

u/[deleted] Mar 19 '19

You don't have to await the returned promise of an async function. Also, data is a promise. Don't know if that's what you intended.

→ More replies (6)

1

u/GBcrazy Mar 19 '19 edited Mar 19 '19

A variation:

const data = async () => Response.prototype.json.call(await fetch('http://someurl.com/')).catch(console.log));

No need for multiple awaits, in fact you don't need it in your function as well. Async function will return a promise anyway so your top most await doesn't do anything

4

u/autobotguy Mar 19 '19

import _ from 'lodash';

4

u/jamesaw22 Mar 19 '19

Destructure from 'loadsh-es' so you can tree shake!

import { values, clone } from 'lodash-es';

→ More replies (2)

2

u/ompelpel Mar 19 '19

const sum = arr.reduce((accumulator, currentVal) => accumulator += currentVal);

Super useful whenever you need to sum all the array’s elements.

6

u/Michie1 Mar 19 '19

Math.sum(...arr)

2

u/BurpingTheWorm1 Mar 18 '19

//Hello World

1

u/tomasswood Mar 19 '19

array.filter(Boolean)

To filter your array to only contain truthy values

1

u/tobegiannis Mar 19 '19

Array.prototype.join is a simple way to handle none, one or many with strings.

const csv = values.join(“,”)

1

u/psayre23 Mar 19 '19

Create an array of the same items...

const fill = (item, length) => Array.from({length}).map(() => item);

const ones = fill(1, 45);

Or creating an array with a range of numbers...

const range = (start, end) => Array.from({length: end - start}).map((_, i) => start + i);

range(0, 3) // [0, 1, 2]

Edit: formatting

1

u/ThePsychopaths Mar 19 '19
let keys = Object.keys(searchParams)
let queryString = keys.length < 2 ? `${keys[0]} = ${ typeof searchParams[keys[0]] === 'string' ? `'${searchParams[keys[0]]}'`: searchParams[keys[0]] }` : keys.reduce((accumulator, value) => `${searchParams[accumulator] == null ? accumulator : ` ${accumulator} = ${ typeof searchParams[accumulator] === 'string' ? `'${searchParams[accumulator]}'`: searchParams[accumulator] } `} AND ${value} = ${ typeof searchParams[value] === 'string' ? `'${searchParams[value]}'` : searchParams[value]} `)

It creates a SQL-like query from json search object

1

u/lordxeon Mar 19 '19

Yea... that is completely unreadable...

1

u/noruthwhatsoever Mar 19 '19

I've been finding myself needing to shallow copy and filter large, normalized objects quite a lot and have developed a handy little chain that gives you quite a fine grain of control over what you can do with it:

const filteredObj = Object.keys(obj)
    .filter(key => (
        obj[key] === 'someCondition' || key !== 'somestring'))
    .reduce((newObj, key) => ({
        ...newObj, [key]: obj[key] }), {});

If any of you folks have a different way of doing this, I'd be interested to see it! And yes I know that with this formatting it's technically not a one-liner but it could be all on one line, it would just be unreadable

1

u/tencircles Mar 19 '19

const demethodize = Function.prototype.bind.bind(Function.prototype.call);

1

u/dai-shi Mar 19 '19

const iota = n => [...Array(n).keys()]

2

u/Shaper_pmp Mar 19 '19

I never understand why people feel the need to populate an array with a sequence of consecutive values. I've spent over 20 years writing javascript and never once encountered a legitimate use-case for doing it.

The only reason I can imagine is if someone wanted to "iterate X times" and was allergic to the simple for loop, so instead they're defining, reserving and populating an entire array in memory just so they can iterate over its array indices and then immediately throw it all away again... but that's pants-on-head crazy code.

Genuinely curious, in case I'm missing something...

→ More replies (8)

1

u/sdiown Mar 19 '19

...arrayVar

1

u/kybernetikos Mar 19 '19 edited Mar 19 '19

Possibly stretching the definition of a one liner, but it can be handy:

const parms = location.search.substr(1).split("&").map((x) => x.split(/=(.*)/)).reduce((acc, [key, value = true]) => (acc[key] = value, acc), {})

1

u/cicadaTree chest hair complexities Mar 19 '19

That's a space ship.

1

u/AlexDeMaster Mar 19 '19

console.log(somethingHere) because that's the best way to debug code, isn't it? :)

1

u/keniafre Mar 19 '19

console.log(...blah, blah, blah) ;

1

u/bminixhofer Mar 19 '19
console.log=(()=>{var a=console.log;return(...b)=>{a(...(!(b.length>>1)&&b[0].charAt?['%c'+b[0],'font:1em Comic Sans MS']:b))}})();

This will change the font of your log to Comic Sans. I don't know what I would do without it.

1

u/supraniti Mar 19 '19

console.log(this);

1

u/davi86d Mar 19 '19

A bit more of debugging:

console.log('%cI am a big fat red log record', 'color: red; background-color: yellow; font-size: x-large') — css formatted console logs, note the '%c' before the logged value

//# sourceURL= 'whatever.js' — let the devtools (at least Chrome) know the name of a dynamically loaded script (loaded for example by jquery's $.load(path)). This allows direct modification of such script inside devtool's 'sources' tab (for the current browser instance - not physical file, of course). Without this the script will be referenced as 'WM#####' and non-modifiable. Note this marker must be inserted on the last row of the script and the script must not be minified (it can, but then you have to do edits on the minified single row. As soon as you use the 'prettify' feature of the devtools it will become unmodifiable again). Then you can save your changes by Ctrl+S without need to reload the page. This actually saves me huge amount of time per day as I am a maintainer of SPApp and each such rebuild&reload takes quite a while

→ More replies (1)

1

u/yuri_auei Mar 19 '19

When i dont want to include a lib with function utilities, i like to access a object property with this function:

const pluck = (...keys) => obj => keys.reduce((result, key) => result && result[key], obj)

1

u/jamesleesaunders Mar 19 '19

I’m ashamed to say it but it is still console.log()

1

u/BalthazarBulldozer Mar 19 '19

console.log()

And THANK GOD for it

1

u/rafaelcastrocouto Mar 19 '19 edited Mar 19 '19
const $ = (selector, startNode = document) => [...startNode.querySelectorAll(selector)];

1

u/delventhalz Mar 19 '19

A range function is a glaring omission from JS, but you can get it with this little one liner:

const range = len => Array.apply(null, Array(len)).map((_, i) => i);

And of course, in the post-ES6 era it’s even easier:

const range = len => [...Array(len).keys()];

1

u/stalet Mar 19 '19

console.log(‘should never happen’);

1

u/piggybanklol Mar 19 '19

// I DON'T KNOW WHAT THIS DOES, SO DO NOT MODIFY

1

u/[deleted] Mar 19 '19

console.table()

1

u/wthit56 Mar 20 '19

var unique_id; while(document.getElementById(unique_id = "id_" + Math.random()));

or

var unique_id; while(document.getElementById(unique_id = "id_" + Math.random().toString().substr(2)));

Generates a DOM ID that doesn't exist within the document.

1

u/every_octopus_ever Mar 20 '19
/** Generates an array with all values from `start` to `end`
  (not including `end`) */
const range = (start, end) =>
  Array.from({ length: end - start }, (_, i) => start + i);

1

u/[deleted] Mar 22 '19
console.log(whatever_i_need);

1

u/ghillerd Mar 19 '19 edited Mar 19 '19

const theOne = list.find(({_id}) => _id === search), and const flattenNested = list.reduce((acc, {sub}) => [...acc, ...sub], []) are good. All the array functions have application as super terse one-liners that aren't even worth making a function for.

Edit: forgot reduce init value

2

u/[deleted] Mar 19 '19

What do these do my friend?

2

u/ghillerd Mar 19 '19

The first one grabs an object out of an array by a property value, and the second flattens nested arrays by property name.

2

u/NoInkling Mar 19 '19

With the latest version of ES that second one becomes:

list.flatMap(({sub}) => sub)

1

u/squoddam Mar 19 '19

log = (val) => (console.log(val), val)

2

u/inkubux Mar 20 '19

Love this one when using pipe or compose