JavaScript 7 Simple One Liners to work with Arrays
As the Java script is widely used, if you are developer, you must get a chance or requirement work with it.
JavaScript syntax and built-in methods allows you to cut down a lot of unnecessary lines in your code and write short, easily readable code.
As we all know less code is performs faster and better. it’s also easy understand, remember and maintain
In this post, we are taking this simplicity other steps forward to see where we can write one-line solutions to some common use cases and problems you’d encounter in development.
So, in this post I am showing 7 simple One liners useful while working with arrays, which we use commonly while web development.
1. Get Sum of Array
Get sum of array of numbers using reduce function. It will only sum the numbers in array if there any string in array it will not sum properly
2. Get unique elements from array
Every language has its own implementation of Hash List, in JavaScript, it is called Set. You can easily get the unique elements from an array using the Set Data Structure,
We can use this behavior to our advantage to remove duplicate items in an array. However, it only works with arrays storing primitive data. So, you’d have to write a multiline solution to remove duplicates in arrays storing objects. But, still, it’s a quite decent method to remove duplicates in simple scenarios.
3. Check if the array is empty
A simple and perfect one-liner to check if an array is empty, will return true or false.
const isEmpty = arr => Array.isArray(arr) && arr.length > 0;
4. Get the intersection of arrays
Getting the intersection / common elements of arrays can be one of the programming problems you run into that might cause you a headache. But there’s no need to because it can all be done with this one-liner — which can be a true headache saver.
Note that this function is capable of getting the intersection of more than just two arrays at a time.
5. Flatten an array
The days where flattening/merging an array can be a real challenge are over, with this neat one-liner.
6. Extract values of a property from an array of objects
With below one liner you can create new array from existing array of object.
7. One liner for Some Basic Actions in array
Remove Items from array
Append Item to array
Sorting Array
Thanks for your valuable time !!
There can be more one liners or even shorter versions of examples above.
Please share your comments and suggestion to improve this blog at: “hello@dineshsoni.in”.
Blog will be Continue with other one liner examples, on next post
JavaScript 7 Simple One Liners to work with Arrays Read More »