Hi All, today I will share some of the Javascript Array tricks which will improve your development skills. In our daily life, we use arrays a lot in javascript application to store data which is very easy to handle in terms of all crud operations related to data we can handle easily in an array. But there are some tasks which take time to do with a javascript array.
We will look into some scenarios which are easy to do but some times we spend a lot of time completing those tasks. These javascript array tricks will help you work with different scenarios related to javascript arrays.
Table of Contents
Shuffle Array
This scenario occurs a lot of times in our application that we have to shuffle the array values and there is no function provided for javascript shuffle array. Here I have created a small snippet to shuffle the array values.
function shuffle(arr) { var i, j, temp; for (i = arr.length - 1; i > 0; i--) { j = Math.floor(Math.random() * (i + 1)); temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } return arr; }
Unique Value
We always have to keep unique values in every dataset we handle. Rarely we accept duplicate values in any dataset and that too depends on use case which is not very common in software development. For this, I will share multiple options to achieve the desired results.
- Using javascript Set() function, this function works with a single value array which means an array of strings, numbers, booleans, etc. Not a good choice for nested object values in an array.
const numArray = [1,2,3,4,2,3,4,5,1,1,2,3,3,4,5,6,7,8,2,4,6]; // With Array.from Function Array.from(new Set(numArray)); // Shorthand with ES6 spread operator [...new Set(numArray)]
- Using Array.filter function, this function returns a new array with elements which is passed the test provided to the function for javascript filter array of objects. Note: filter() does not execute the function for an empty array and it does not change the original value rather creates a new array with all the filtered items and returns to the callback.
const data = [ {id: 1, name: 'Lemon'}, {id: 2, name: 'Mint'}, {id: 3, name: 'Mango'}, {id: 4, name: 'Apple'}, {id: 5, name: 'Lemon'}, {id: 6, name: 'Mint'}, {id: 7, name: 'Mango'}, {id: 8, name: 'Apple'}, ] function findUnique(data) { return data.filter((value, index, array) => { if(array.findIndex(item => item.name === value.name) === index) { return value; } }) }
- Lodash (uniqBy()), creates a duplicate free version of an array using SameValueZero for equality comparisons, in which only the first occurrence of each element is kept. The order of result values is determined to the order they occur in the array.
import {uniqBy} from 'lodash' const data = [ {id: 1, name: 'Lemon'}, {id: 2, name: 'Mint'}, {id: 3, name: 'Mango'}, {id: 4, name: 'Apple'}, {id: 5, name: 'Lemon'}, {id: 6, name: 'Mint'}, {id: 7, name: 'Mango'}, {id: 8, name: 'Apple'}, ] function findUnique(data) { return uniqBy(data, e => { return e.name }) }
Sort Javascript array of objects by property
Javascript array provides a sort function that works perfectly with an array of numbers, strings, booleans and etc, but when it comes to the array of objects it does not work that effectively. To tackle this we can use a callback in array.sort function and do our comparison to sort the values and return the sorted array.
We will use compare function to sort the data which is an array of objects. Consider A and B to be the values to compare. From our compare function we will have returned values as per conditions below:
- less than 0 — A comes before B
- greater than 0 — B comes before A
- equal to 0 — A and B are left unchanged with respect to each other.
const data = [ {id: 1, name: 'Lemon', type: 'fruit'}, {id: 2, name: 'Mint', type: 'vegetable'}, {id: 3, name: 'Mango', type: 'grain'}, {id: 4, name: 'Apple', type: 'fruit'}, {id: 5, name: 'Lemon', type: 'vegetable'}, {id: 6, name: 'Mint', type: 'fruit'}, {id: 7, name: 'Mango', type: 'fruit'}, {id: 8, name: 'Apple', type: 'grain'}, ] function compare(a, b) { // Use toLowerCase() to ignore character casing const typeA = a.type.toLowerCase(); const typeB = b.type.toLowerCase(); let comparison = 0; if (typeA > typeB) { comparison = 1; } else if (typeA < typeB) { comparison = -1; } return comparison; } data.sort(compare)
Array to comma separated string
Javascript has a very easy and simple way of achieving this task, but most of the new javascript developers don’t know how we can do change array to comma separated string with one simple javascript array function and they end up searching on StackOverflow and go through multiple questions and pages which make them waste their time in this small task. So let’s see how we can do this with one line of code.
const data = ['Mango', 'Apple', 'Banana', 'Peach'] data.join(','); // return "Mango,Apple,Banana,Peach"
Select a single element from an array
For this task we can use multiple options, we can use javascript forEach function and have an if-else check to pull out value, we can use javascript filter function and filter the value, but the drawback in using javascript foreach and filter functions are
- In forEach it will unnecessarily iterate over the array and we have to write additional if else statement to pull out the desired value.
- In filter function, we have a simple comparison operation but it will return an array which we don’t want instead we want the single object from an array as per the given condition.
To solve this we will use javascript array find function to find the exact element from an array and return that object, here we don’t need to use an if-else statement to check if element meets our condition or not. Below is the example of the javascript array find function.
const data = [ {id: 1, name: 'Lemon'}, {id: 2, name: 'Mint'}, {id: 3, name: 'Mango'}, {id: 4, name: 'Apple'} ] const value = data.find(item => item.name === 'Apple') // value = {id: 4, name: 'Apple'}
So this is it for javascript array tricks post today, I will come up with more Javascript functions and tricks which will help you to improve your skill and increase your productivity.
You can visit my Instagram post on Types of Javascript functions
View my post on Creating reusable table component in React