13 useful tricks for working with arrays in JavaScript that may come in handy

Arrays are one of the most popular data structures in JavaScript because they are used to store data. In addition, arrays provide many opportunities for working with this very data. Understanding that for those who are at the beginning of the way of learning JavaScript, arrays are one of the most basic topics, in this article I would like to introduce you to some useful tricks that you might not know about. Let's start.



1. How to leave only unique values ​​in an array



This is a very popular question during an interview for the position of a Javascript developer. Here is a quick and easy solution to this problem. First you need to get the unique values ​​of the array, for this you can use new Set()



( approx. Re .: the Set data structure stores only unique values ). Next, you need to convert the Set data structure into an array. I want to introduce you to two ways how to do this: the first - using the from()



method, the second - using the spread ( "…"



) operator.



 const fruits = ['banana', 'apple', 'orange', 'watermelon', 'apple', 'orange', 'grape', 'apple']; //   const uniqueFruits = Array.from(new Set(fruits)); console.log(uniqueFruits); //  ['banana', 'apple', 'orange', 'watermelon', 'grape'] //   const uniqueFruits2 = [...new Set(fruits)]; console.log(uniqueFruits2); //  ['banana', 'apple', 'orange', 'watermelon', 'grape']
      
      





Easy, right?



2. How to replace values ​​in an array



There are situations when you need to replace the values ​​in the array with other values. To do this, there is a good method that you may not have known about - the splice(start, value to remove, values to add)



method, where start



is the index number from which we want to remove the elements of the array, value to remove



is the number of elements that we want to delete, and values to add



are the elements that we want to insert in the place of the deleted ones:



 const fruits = ['banana', 'apple', 'orange', 'watermelon', 'apple', 'orange', 'grape', 'apple']; fruits.splice(0, 2, 'potato', 'tomato'); console.log(fruits); //  ["potato", "tomato", "orange", "watermelon", "apple", "orange", "grape", "apple"]
      
      





3. How to transform an array without using the map()



method



Probably everyone knows the map()



array method, but there is another solution that can be used to obtain a similar effect and clean code. To do this, we can use the from()



method:



 const friends = [ { name: 'John', age: 22 }, { name: 'Peter', age: 23 }, { name: 'Mark', age: 24 }, { name: 'Maria', age: 22 }, { name: 'Monica', age: 21 }, { name: 'Martha', age: 19 }, ] const friendsNames = Array.from(friends, ({name}) => name); console.log(friendsNames); //  ['John', 'Peter', 'Mark', 'Maria', 'Monica', 'Martha']
      
      





4. How to quickly clear an array



For example, we have an array in which there are many elements. We need to clean it (no matter for what purpose), while we do not want to delete elements one by one. This is very simple to do with one line of code. To clear the array, we need to set the length of the array to 0, and that’s it!



 const fruits = ['banana', 'apple', 'orange', 'watermelon', 'apple', 'orange', 'grape', 'apple']; fruits.length = 0; console.log(fruits); //  []
      
      





5. How to convert an array to an object



This situation happens: we have an array, but we need an object (again, no matter for what purpose) with this data, and the fastest way to convert the array to an object is to use the spread ( "..."



) operator:



 const fruits = ['banana', 'apple', 'orange', 'watermelon', 'apple', 'orange', 'grape', 'apple']; const fruitsObj = { ...fruits }; console.log(fruitsObj); //  {0: 'banana', 1: 'apple', 2: 'orange', 3: 'watermelon', 4: 'apple', 5: 'orange', 6: 'grape', 7: 'apple'}
      
      





6. How to fill an array with the same values



There are different situations when we want to create an array and fill it with some values, or we need an array with the same values. The fill()



method for such tasks is a great solution:



 const newArray = new Array(10).fill('1'); console.log(newArray); //  ["1", "1", "1", "1", "1", "1", "1", "1", "1", "1"]
      
      





7. How to combine more than two arrays



Do you know how to combine arrays into one without using the concat()



method? There is an easy way to combine any number of arrays into one array with one line of code. As you probably already understood, the spread ( "..."



) operator is a pretty useful tool when working with arrays, as in this case:



 const fruits = ['apple', 'banana', 'orange']; const meat = ['poultry', 'beef', 'fish']; const vegetables = ['potato', 'tomato', 'cucumber']; const food = [...fruits, ...meat, ...vegetables]; console.log(food); //  ["apple", "banana", "orange", "poultry", "beef", "fish", "potato", "tomato", "cucumber"]
      
      





8. How to find the intersection of two arrays



You can face this task in any JavaScript interview, because its solution shows your knowledge of array methods, as well as how you think. To find the common values ​​of the two arrays, we will use one of the previously discussed methods in this article to make sure that the values ​​in the array that we are checking are not duplicated. In addition, we will use the filter()



and includes()



methods. As a result, we get an array with elements that are represented in both arrays:



 const numOne = [0, 2, 4, 6, 8, 8]; const numTwo = [1, 2, 3, 4, 5, 6]; const duplicatedValues = [...new Set(numOne)].filter(item => numTwo.includes(item)); console.log(duplicatedValues); //  [2, 4, 6]
      
      





9. How to remove false values ​​from an array



To get started, let's define false values. In Javascript, false values ​​are: false



, 0 , "" , null



, NaN



and undefined



. Now we can figure out how to remove such values ​​from our array. To achieve this, we need the filter()



method:



 const mixedArr = [0, 'blue', '', NaN, 9, true, undefined, 'white', false]; const trueArr = mixedArr.filter(Boolean); console.log(trueArr); //  ["blue", 9, true, "white"]
      
      





10. How to get a random array value



Sometimes we need to select a random array value. To make the solution simple, short and fast, we can get a random index number according to the length of the array. Take a look at this example:



 const colors = ['blue', 'white', 'green', 'navy', 'pink', 'purple', 'orange', 'yellow', 'black', 'brown']; const randomColor = colors[(Math.floor(Math.random() * (colors.length)))]; console.log(randomColor); //     
      
      





11. How to expand the array in the opposite direction



When we need to “flip” our array, there is no need to create it through complex loops and functions, because there is a simple reverse()



array method that does all of this for us, and with one line of code we can “flip” our array:



 const colors = ['blue', 'white', 'green', 'navy', 'pink', 'purple', 'orange', 'yellow', 'black', 'brown']; const reversedColors = colors.reverse(); console.log(reversedColors); //  ["brown", "black", "yellow", "orange", "purple", "pink", "navy", "green", "white", "blue"]
      
      





12. lastIndexOf()



method



JavaScript has an interesting lastIndexOf(elem)



method that lets you find the index of the last occurrence of an elem



element. For example, if our array has duplicate values, we can find the position of the last occurrence in it. Take a look at the following code example:



 const nums = [1, 5, 2, 6, 3, 5, 2, 3, 6, 5, 2, 7]; const lastIndex = nums.lastIndexOf(5); console.log(lastIndex); //  9
      
      





13. How to sum all the values ​​in an array



Another popular question during an interview for a JavaScript developer position. The sum of all elements can be found in one line of code, if you know the reduce()



method:



 const nums = [1, 5, 2, 6]; const sum = nums.reduce((x, y) => x + y); console.log(sum); //  14
      
      





Conclusion



In this article, I introduced you to 13 useful tricks to help you write clean and concise code. In addition, do not forget that there are many different tricks that you can use in Javascript and which are worth studying not only for working with arrays, but also for other data structures. I hope that you liked the solutions presented in the article and you will use them to improve the development process.



Have a nice writing code!



All Articles