JavaScript tricks: Array and Objects
Have you thought about what the recent tricks in JavaScript you could add to your programming skills that would help you write more concise and clean code? Then I have something for you; it helped me write good code, reducing the amount of code I need to write before achieving my desired outcome.
This tutorial would introduce you to recent Array and object operation that were implemented recently in JavaScript Es6. Stuffs like swapping of arrays’ value without introducing a third variable.
This article would benefit beginners like me and also developers who don’t know about the recent features yet.
Arrays and objects are reference data types in JavaScript. They are stored on the heap. This means that they are stored in a pointer to a location in memory.
in JavaScript, reference data type are technically objects meaning that an array is also an object.
Arrays
Arrays are objects in JavaScript. They store data in sequence and this data can be accessed with the numbered index. Array indexes are zero based, this means that the first element in the array is stored at the 0th index and the second element on the 1st index and so on.
It is written as a list of values in squared brackets and are separated with comma.
Here are some simple array tricks.
Array swap() method
We can swap the position of elements in an array using the array swap() method. To swap arrays normally requires us to crate a new variable.
Here,we want the swap the element at the second index("four") with the element at the third index("three").
const myArray = ["one", "two", "four", "three"];
// create new variable
const swap = myArray[2];
myArray[2] = myArray[3];
myArray[3] = swap;
console.log(myArray);
//-> ["one", "two", "three", "four"]
We use swap variable to store the value of the second index("four"), then we put the third index("three") in place of the second index, then we assign the swap variable to the third index.
But we can swap arrays without having to create new variables using this syntax.
const myArray = ["one", "two", "four", "three"];
[myArray[2], myArray[3]] = [myArray[3], myArray[2]];
console.log(myArray);
//-> ["one", "two", "three", "four"]
Destructuring Array
Destructuring is a fancy way in JavaScript of deconstructing arrays.
It is s way of extracting multiple values of data stored in an array.
If we want to get the first element out of an array, we can get it by accessing the first index.
const myArray =[1, 2, 3, 4];
const first = myArray[0];
console.log(first);
//-> 1
This is very straightforward. But what if we want to get the first 2 elements in two separate variables? Then, we'll have to assign them one after the other like this:
const myArray =[1, 2, 3, 4];
const first = myArray[0];
const second = myArray[1];
console.log(first);
//-> 1
console.log(second);
//-> 2
This is not a bad way to write your code but it can be simplified with Destructuring.
const myArray =[1, 2, 3, 4];
const[first, second] = myArray;
console.log(first);
//-> 1
console.log(second);
//-> 2
What this does is that it tell JavaScript to assign the first element in myArray to the first variable in the square bracket which in this case is first and assign the second element in myArray to the second variable in the square bracket. This will continue till there are no more variables left in the squared bracket.
If we want to skip an element in , let's say we want the first and last element, we would use a comma instead of a variable.
This comma tells JavaScript to skip the the element in the array.
const myArray =[1, 2, 3, 4];
const[first, , ,last] = myArray;
console.log(first);
//-> 1
console.log(last);
//-> 4
Spread operator
When we don't want only the first two or three elements, but maybe we want all the elements except the elements except the first, second, or the first two or any amount of elements, that's where the spread operator comes in.
The spread operator is used is used to expand or spread an array, it expands an array into individual elements. The syntax is three dots (…) followed by the array.
const myArray = [1, 2, 3, 4];
const [first, …rest] = myArray;
console.log(first);
//-> 1
console.log(rest);
//-> [2, 3, 4]
We can also use the spread operator to concatenate arrays.
const myArray1 = ["A", "B", "C"];
const myArray2 = ["D", "E", "F"];
const newArray = [...myArray1,...myArray2];
console.log(newArray);
//-> ["A", "B", "C", "D", "E", "F"]
The spread operator doesn't only enable you concatenate arrays, it also enables you to add individual elements to the arrays even as you concatenate the arrays.
const myArray1 = ["A", "B", "C"];
const myArray2 = ["D", "E", "F"];
const newArray = [...myArray1, 1, 2,...myArray2,"G", "H"];
console.log(newArray);
//-> ["A", "B", "C", 1, 2 "D", "E", "F", "G", "H"]
Cloning an Array
The spread operator can be used to clone an array. Let's say we have an array and we want to make a copy that we can do anything with but then still have the original array. We can clone the array using the spread operator but first, Iet's see how we can do it with the good old for() loop.
const num = ["A", "B", "C"];
const numCopy = [];
for (i = 0; i < num.length;i++) {
numCopy[i] = num[i];
}
console.log(numCopy);
//-> ["A", "B", "C"]
Now let's see how we can clone this sam array using the spread operator.
const num = ["A", "B", "C"];
const numCopy = […num];
console.log(numCopy);
//-> ["A", "B", "C"]
Array methods
Find() method: The array.find() method is used to get the first element in an array that satisfies the testing condition.
const array = [2, 4, 6, 8];
// testing condition (element < 6)
const search = array.find(function (element) {
return element < 6;
} );
console.log(search);
//-> 2
In this example, the find() method outputs 2 because that is the first element in the array that satisfies the testing condition (element < 6).
Every() method: The every() method returns true if all the elements in the array satisfies the testing condition.
The every() method returns false when it finds an array that returns a false value.
const array = [10, 20, 30, 40];
const num = array.every(function (numbers) {
return numbers > 9;
} );
console.log(num);
//-> true
Objects
An object is a collection of key-value pairs used to store multiple data. Objects are mutable and can store more than single values of data, these values are called properties.
Destructuring Objects
Just like array, destructuring an object is pretty easy but this time, we put the properties in curly brackets.
const male = {
name: "Dalu",
age: 15
}
const {name, age} = male;
console.log(name);
//-> Dalu
console.log(age);
//-> 15
We can use the same variable names for our destructured variables as we used for our objects, this will work perfectly. But we can also rename the variables as well.
const male = {
name: "Dalu",
age: 15
}
const {name: firstName, age: years} = male;
console.log(firstName);
//-> Dalu
console.log(years);
//-> 15
Nested Objects
We can access objects that are nested in other objects with destucturing.
const male = {
name: "Dalu",
age: 15,
clothColor = {
shirt: "blue",
polo: "red"
}
}
const {name,clothColor: {polo} } = male;
console.log(name);
//-> Dalu
console.log(polo);
//-> red
Here, we map the clothColor property and didn't assign it to any variable, instead, we deconstructed the element into the variable polo.
Object Spread Operator
Just like arrays, we can also spread and clone objects using the spread operator.
const male = {
name: "Dalu",
age: 15,
cloth: "jean"
}
const { name,...rest} = male;
console.log(name);
//-> Dalu
console.log(rest);
//->{"age": 15, "cloth": "jean"}
You'll notice that a new object is formed and all the properties that are not deconstructed are added to a new object
This way, we can clone objects leaving out some properties.
Like arrays, we can concatenate objects using the spread operator. This will overwrite any value that is in both objects and replace it with the one that was defined last.
const male = {
name: "Dalu",
age: 15
}
const female = {
age: 20,
cloth: "jean"
}
const both = {...male,...female}
console.log(both);
//-> {"name": "Dalu", "age": 20, "cloth": "jean"}
One more thing that I haven't mentioned; we can nest arrays inside objects and objects inside arrays, which ever way we want.
Let's say we have a list of contact names and numbers in an object that's nested in an array and we want to get the number of a person when we input the name of the person.
First, we create an array that has 3 objects as its properties. Each of these properties(objects) represents a person so it includes the persons name, number and likes(which is another array nested in the object). Then we iterate through tthe array using the arr.length() method in a for loop. Here's how it looks.
let contact = [
{
"firstname": "sandra",
"surname": "john",
"number": 2348103322200,
"likes": ["indomie", "bread"]
},
{
"firstname": "dalu",
"surname": "lawrence",
"number": 2348190876543,
"likes": ["ink", "bear"]
},
{
"firstname": "paul",
"surname": "dawson" ,
"number": 2348130564780,
"likes": ["gun", "beed"]
}
]
function profile(name, prop) {
for (i = 0; i < contact.length; i++){
if (contact[i].firstname === name) {
return contact[i][prop] || "no such property";
}
} return "no such contact";
}
data = profile("dalu", "number");
console.log(data);
//->2348190876543
This example isn't about the function but just to illustrate that we can nest arrays inside objects and vice versa.
Conclusion
In this article, we covered a few array tricks including swapping arrays and cloning arrays. We also covered objects destructuring and the spred operator which makes clonining objects easier.
Next time you're programming, do try to use this operator to improve the quality of your code.
If you have a use-case that requires advanced functionality, checkout this W3schools reference.
Outlines:
Brief introduction to Array and objects as data structures
- Brief explanation of the nature of Array in contrast to that of objects.
Tricks in Array
Swapping
Destructuring, and spread operator.
Using spread operator for cloning in Array’s operations.
Array methods
find method
every method
findIndex method
Tricks in objects
Destructuring in object
Shallow cloning in objects using spread operators
Conclusion