DEV Community

Cover image for Have a Handy JS Snippet You Want to Share?
Nick Taylor
Nick Taylor Subscriber

Posted on • Edited on • Originally published at iamdeveloper.com

Have a Handy JS Snippet You Want to Share?

So it's pretty simple. I'm looking for one or two lines of JavaScript that do something useful.

I'll get the ball rolling and start with some examples:

  • Shallow array clone via Array spread.
const originalArray = [1, 2, 3];
const shallowArrayClone = [...originalArray];

Enter fullscreen mode Exit fullscreen mode
  • Shallow array clone via Array.protoype.slice.
const originalArray = [1, 2, 3];
const shallowArrayClone = originalArray.slice();

Enter fullscreen mode Exit fullscreen mode

  • Shallow clone of an object via object spread.
const originalObject = { a:1, b: 2, c: 3 };
const shallowObjectClone = {...originalObject};

Enter fullscreen mode Exit fullscreen mode
  • Shallow clone of an object via object spread with one property overridden.
const originalObject = { a:1, b: 2, c: 3 };
const shallowObjectClone = {...originalObject, c: 45 };

Enter fullscreen mode Exit fullscreen mode
  • Get unique values of an array using Set
const arrayWithDuplicateValues = [1, 2, 3, 3, 1, 5];
const uniqueArray = Array.from(new Set(arrayWithDuplicateValues);
Enter fullscreen mode Exit fullscreen mode

or

const arrayWithDuplicateValues = [1, 2, 3, 3, 1, 5];
const uniqueArray = [...new Set(arrayWithDuplicateValues)];
Enter fullscreen mode Exit fullscreen mode
  • See if two arrays have the same values (unordered and for primitive values).
const a = [1, 2, 3];
const b = [2, 3, 4];

const uniques = new Set(a.concat(b));
const haveSameValues = uniques.length === a.length // or uniques.length === b.length;
Enter fullscreen mode Exit fullscreen mode
  • Flatten an array with the ES spread operator and Array.prototype.concat. Great tip care of Jonathan Z. White.


const arrayToFlatten = [ [1,2,3], [4,5,6], [7,8,9] ];
const flattenedArray = [].concat(...arrayToFlatten);
Enter fullscreen mode Exit fullscreen mode

2020 Update for the above is

[ [1,2,3], [4,5,6], [7,8,9] ].flatMap(x=>x)
Enter fullscreen mode Exit fullscreen mode

And go!

Cover image care of Flickr user Wayne Grivell.

Top comments (17)

Collapse
 
prodigalknight profile image
RevanProdigalKnight • Edited

Another one I just remembered:

// Automatically escapes all backslashes in the RegExp when stringifying
const stringWithEscapedBackslashes = /\\\\\\this \\\string has lots\ of \\\\backslashes for \\ some reason./.source;
// yields "\\\\\\\\\\\\this \\\\\\string has lots\\ of \\\\\\\\backslashes for \\\\ some reason."
Collapse
 
nickytonline profile image
Nick Taylor

It looks like the escaping only works in FireFox according to the MDN docs, RegExp.prototype.source (see Browser Compatibilty section).

Collapse
 
prodigalknight profile image
RevanProdigalKnight • Edited

Hmm. I verified that the MDN isn't just out of date by testing in Chrome. I can't remember the context I was using that snippet in precisely, but I do remember it was designed to run in IE10+, Chrome, and Firefox.

I may have just been using it so I wouldn't have to escape all my backslashes for a string.

Thread Thread
 
nickytonline profile image
Nick Taylor

I tried in Chrome yesterday and it doesn't error out, but it just doesn't escape.

Collapse
 
blouzada profile image
Bruno Louzada

Wow

Collapse
 
aravindballa profile image
Aravind Balla • Edited

An amazing line from @wesbos podcast syntaxfm

await (await fetch('https://api.github.com/users/wesbos')).json();
Enter fullscreen mode Exit fullscreen mode
Collapse
 
juliani profile image
Julian Iaquinandi

I've not had a chance to listen to the episode yet. Any Chance you can explain this one? Thought I had started to understand async/ await until I saw this! Thanks.

Collapse
 
aravindballa profile image
Aravind Balla • Edited

Let me break that up.

const response = await fetch('https://api.github.com/users/wesbos');

const data = await response.json(); //this gives us the JSON data from the response.
Enter fullscreen mode Exit fullscreen mode

Previously it used to be,

fetch('https://api.github.com/users/wesbos')
.then(res => res.json()) //json() also returns a promise
.then(data => {console.log(data)});

Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
juliani profile image
Julian Iaquinandi

Ahhh I see, that's amazing thanks for that! <3

Thread Thread
 
wesbos profile image
Wes Bos

Thanks! I just clarified this in a tweet:

twitter.com/wesbos/status/95583181...

Thread Thread
 
juliani profile image
Julian Iaquinandi

Thanks Wes, keep up the good work! Loving them tasty treats :P

Collapse
 
aarohmankad profile image
Aaroh Mankad • Edited

Here's a super easy way to remove duplicates from an array (by using the definition of a Set)!


const unique = (arr) => [...new Set(arr)]

// [1, 2, 3, 4, 5]
console.log(unique([1, 1, 2, 3, 4, 5, 5]))

Collapse
 
nickytonline profile image
Nick Taylor

Yup that's a good one, although I already have it up top 😺 .

Collapse
 
aarohmankad profile image
Aaroh Mankad

Oh haha, didn't see that one!

Collapse
 
mschleeweiss profile image
Marc Schleeweiß

You have an array with keys and one with values and want to merge them into an object?

keys = ["a", "b", "c"]
values = [1, 2, 3]

keys.reduce((obj, k, i) => ({...obj, [k]: values[i] }), {})
// result is {a: 1, b: 2, c: 3}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
prodigalknight profile image
RevanProdigalKnight • Edited

Quick-and-easy deferred promise (like from q.defer()) - handy for modal dialogs:

class Deferred {
  constructor() {
    this.promise = new Promise((resolve, reject) => {
      this.resolve = resolve;
      this.reject = reject;
    });
  }
}

// example
function dialog() {
  const deferred = new Deferred();

  // create dialog here
  ...

  // Finally, set up the button click handlers
  dialog.okButton.onclick = deferred.resolve;
  dialog.cancelButton.onclick = deferred.reject;

  return deferred.promise;
}

// Alternatively
function dialog() {
  const { promise, resolve, reject } = new Deferred();

  // etc...

  dialog.okButton.onclick = resolve;
  dialog.cancelButton.onclick = reject;

  return promise;
}

dialog().then(/* success! */, /* cancelled */);

Better than wrapping all of that code inside of a Promise constructor every time, in my opinion.

Collapse
 
jarpi profile image
Josep • Edited

Quick unhasher (not a generic one, but it does the job)



const seed = 7
const prime = 37
const letters = "acdegilmnoprstuw"

const unhash = (hash, acc, letterOffset = 0) => {
  if (hash === seed) return acc
  for (;hash%prime>0;hash--,letterOffset++);
  return unhash(hash/prime, letters[letterOffset] + acc)
}