Have a Handy JS Snippet You Want to Share?
•
2 min read
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];- Shallow array clone via
Array.protoype.slice.
const originalArray = [1, 2, 3];const shallowArrayClone = originalArray.slice();You could just do const new array = this.props.slice().sort()
— Nick Taylor (@nickytonline) September 15, 2017
- Shallow clone of an object via object spread.
const originalObject = { a:1, b: 2, c: 3 };const shallowObjectClone = {...originalObject};- 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 };- Get unique values of an array using
Set
const arrayWithDuplicateValues = [1, 2, 3, 3, 1, 5];const uniqueArray = Array.from(new Set(arrayWithDuplicateValues);or
const arrayWithDuplicateValues = [1, 2, 3, 3, 1, 5];const uniqueArray = [...new Set(arrayWithDuplicateValues)];- 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;- Flatten an array with the ES spread operator and Array.prototype.concat. Great tip care of Jonathan Z. White.
TIL you can flatten multi-dimensional arrays using concat and the ES6 spread operator ☀️ pic.twitter.com/zPK4a490w2
— Jonathan Z. White 👾 (@JonathanZWhite) April 16, 2018
const arrayToFlatten = [ [1,2,3], [4,5,6], [7,8,9] ];const flattenedArray = [].concat(...arrayToFlatten);2020 Update for the above is
[ [1,2,3], [4,5,6], [7,8,9] ].flatMap(x=>x)And go!
Cover image care of Flickr user Wayne Grivell.