An Array is a data type in JavaScript used for storing a collection of like data. In our daily activities, we always find ourselves grouping things that are alike together, sometimes we even find ourselves being grouped with people that we share a common function or attribute.
An array is how we can represent this group together in javascript. Different names can be used to mean an array, some are collection, group, list, etc. But with the names, I believe you can get an idea of what Javascript array is all about.
Say we have a list (array, group, collection) of all the student's names of a class, we could represent this in JavaScript thus
const studentNames = [
'Dwayne Johnson',
'Lionel Messi',
'Kevin Hart',
'Elon Musk',
'Lebron James',
];
The array studentNames
represents the names of students in a class. Each student's name can be referred to as an item or element or member.
To access a member of an array we use the bracket notation i.e
studentNames[0]; // returns 'Dwayne Johnson
Javascript array indexes start with 0, in other words, the first item is 0 and the second item is 1.
Modifying Array Items
We have looked at declaring arrays, and accessing them individually, now let's talk about making changes to an array. In JavaScript, we can add, remove and change items in an array. JavaScript provides a lot of methods to do these.
It is important to note that these methods or ways of modifying array items listed in this section will actually change the array. In other words, these guys will actually make changes to the array and the effects of these changes will be seen on the array even after the use of these methods. If you don't understand this now, never mind you'll get the full picture as you continue.
Adding Items to an array
Using the push()
method
With the JavaScript array push()
method, you can append items to the end of an array.
const numbers = [1, 2, 3, 4, 5];
numbers.push(6);
console.log(numbers); // result: [1, 2, 3, 4, 5, 6]
Easy right! The push()
method can take more than one argument, so you can add multiple items at a go. You should also try to not add more than three values as an argument as this would not be a good convention for readability.
But what if you have 10 items to add to the array. This is what you should do, make an array containing these new items to add and pass the array as an argument for the push()
method using the spread operator syntax (...
).
const numbers = [1, 2, 3, 4, 5];
const numbersToAppend = [6, 7, 8, 9, 10];
numbers.push(...numbersToAppend);
console.log(numbers); // result: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Not using the spread operator, in this case, will lead to a multidimensional array, which we don't want.
Hey, since you are reading this, i think you might be interested in 20+ Places to Learn Programming for Free
Using the unshift()
method
With the JavaScript array unshift()
method, you can add items to the beginning of an array.
const numbers = [1, 2, 3, 4, 5];
numbers.unshift(0);
console.log(numbers); // result: [0, 1, 2, 3, 4, 5]
Easy right! Just like the push()
method, the ...unshift method can take more than one argument, so we can add multiple items. Do not also forget to use an array along with a spread operator to add multiple items for the sake of readability.
Using the splice()
method
We've looked at two methods that can only append items to the end and beginning of an array respectively, what if I want to add items anywhere else? Well, JavaScript says not to worry, the splice method will do just that.
With the JavaScript array splice()
method, you can add items at any position in an array. The splice()
method can take multiple arguments, but there are three arguments that are required to add an item.
const languages = ['Python', 'Javascript', 'Java', 'Go'];
languages.splice(2, 0, 'PHP');
console.log(languages); // result: ['Python', 'Javascript', 'PHP', 'Java', 'Go']
The first parameter defines the position(index) where new items should be added.
The second parameter defines the number of items to be removed from that array - we don't want to remove so we can leave this at 0.
The last parameter and every other parameter after it defines the item(s) to be added to the specified position.
const languages = ['Python', 'Javascript', 'Java', 'Go'];
languages.splice(2, 0, 'PHP', 'C++', 'C#');
console.log(languages); // result: ['Python', 'Javascript', 'PHP', 'C++', 'C#', Java', 'Go']
So with the splice method, we can add multiple items at any position we want. Again if you intend to add more than one item I'd suggest you make an array and use the spread operator to do the needful. As explained in the push()
method above.
const numbers = [1, 2, 3, 4, 5];
const numbersToAppend = [6, 7, 8, 9, 10];
numbers.splice(5, 0, ...numbersToAppend);
console.log(numbers); // result: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Imagine writing it like this
const numbers = [1, 2, 3, 4, 5];
numbers.splice(5, 0, 6, 7, 8, 9, 10);
console.log(numbers); // result: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
If you should take a break from coding and when you come back to this code above. Trust me, you would be as confused as someone who knows nothing about coding :). Because maybe by then you've probably forgotten what the first parameter in the splice method does. You see.
Hey there again. Since you studying Javascript, I figured this might be useful, The roadmap to become a Web Developer in 2021.
Using the Array accessors.
I am sure you are curious to know what array accessors are, well I hate to break it to you, but it doesn't mean anything special. I made it up.
The reason I called it array accessors is because we will use the usual way of accessing items in an array to add items.
const numbers = [1, 2, 3, 4, 5];
numbers[7] = 8;
console.log(numbers); // result: [1, 2, 3, 4, 5, undefined, undefined, 8]
Using the example above can lead to undefined holes in our arrays which we don't want. But to add items to the end of an array at the same time avoid those undefined holes, we need to get the length (number of items in the array) of the array.
Because JavaScript array is zero indexes, it means the length of the array is always one step ahead of the index of the last item. This will enable us to add items to the end without altering the last item of the array. So to add another item to the end of an array we say
const numbers = [1, 2, 3, 4, 5];
numbers[numbers.length] = 6;
console.log(numbers); // result: [1, 2, 3, 4, 5, 6]
How this works is simple, we get the length of the array using numbers.length
, then we set it as an index for a new item.
With this method, we can only add items one at a time. But we can add multiple items by creating an array for these items to be added, and looping them. Like this
const numbers = [1, 2, 3, 4, 5];
const numbersToAppend = [6, 7, 8, 9, 10];
numbersToAppend.forEach((number) => {
numbers[numbers.length] = number;
});
console.log(numbers); // result: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
We will talk about loops in the latter part of this article.
Removing Items from an array
The delete
keyword which would have been my favorite is the one you should never use.
Using the pop()
method
As the push()
method is to add items to the end of an array so is the pop()
method to removing an item from the end of an array.
The JavaScript array method pop()
will remove the last item in an array. It usually returns the removed item as its value.
const numbers = [1, 2, 3, 4, 5];
const removedNum = numbers.pop();
console.log(numbers); // result: [1, 2, 3, 4]
console.log(removedNum); // result: 5
This method doesn't take any parameters.
Using the shift()
method.
The JavaScript array method shift()
will remove the first item in an array. It usually returns the removed item as its value.
This method doesn't take any parameters.
const numbers = [1, 2, 3, 4, 5];
const removedNum = numbers.shift();
console.log(numbers); // result: [2, 3, 4, 5]
console.log(removedNum); // result: 1
Using the splice()
method
Just as we can add items with this method, we can also remove items. Removing items with this method requires two arguments I.e
const numbers = [1, 2, 3, 4, 5];
numbers.splice(4, 1);
console.log(numbers); // result: [1, 2, 3, 4]
- The first parameter indicates the position(index) where the items should be removed from.
- The last parameter indicates the number of items to be removed.
The
splice()
method will return an array of the removed item(s).
const numbers = [1, 2, 3, 4, 5];
const removedNums = numbers.splice(3, 2);
console.log(numbers); // result: [1, 2, 3]
console.log(removedNums); // result: [4, 5]
So this is one of the ways to remove multiple items from an array, there are others, which we will make mention of next.
Using the Length property
With the length property, we can remove as many items as we want from the end of an array.
const numbers = [1, 2, 3, 4, 5];
numbers.length = numbers.length - 1;
console.log(numbers); // result: [1, 2, 3, 4]
The 1 indicates the number of items to be removed from the end of the array. Now the way this works is this. Normally with the length property, we can redefine a length for an array and the array will change e.g
const studentNames = [
'Dwayne Johnson',
'Lionel Messi',
'Kevin Hart',
'Elon Musk',
'Lebron James',
];
studentNames.length = 3;
console.log(studentNames); // result: ['Dwayne Johnson', 'Lionel Messi', 'Kevin Hart']
Now recall that we said the length of an array is one higher than the index of the last item of that array, so we will redefine the length of the array to the index of the last item by removing one from the length of the array. When we remove two, we are saying we want to remove the last two items (by saying the new length of the array should be equal to the current length - 2).
Are you preparing for an interview? Here is a Codecademy course to help you practice Technical interview questions in Javascript
Replacing Items in an Array
How would we change or replace items in an array? There are two ways that we can do this
Using the Array Accessors.
Simply access the item you which to change by using its index i.e
const numbers = [1, 2, 3, 4, 5];
numbers[2] = 25;
console.log(numbers); // result: [1, 2, 25, 4, 5]
One of the ways you can use to get the index of an item using the item is the indexOf()
method.
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.indexOf(3)); // result: 2
With the indexOf method, you don't need to know the index of the item before using it elsewhere. You simply need to know the item.
Using the splice()
method.
This guy is just everywhere.
Apart from being able to add and remove with the splice()
method, we can also replace or change items in an array with it. Here is how
const numbers = [1, 2, 3, 4, 5];
numbers.splice(3, 1, 20); // replacing index 3 (which is 4) with 20
console.log(numbers); // result: [1, 2, 3, 20, 5]
- The first parameter is the position(index) of the item to change or replace.
- The second is the number of items we intend to change from the position already specified in the first parameter.
- The third and every other parameter define the items we intend to change the removed items with.
Here we have an array of 5 sorted numbers with a difference of one, if want to replace 4 and 5 with 7 and 8, this is what we will do
const numbers = [1, 2, 3, 4, 5];
numbers.splice(3, 2, 7, 8);
console.log(numbers); // result: [1, 2, 3, 7, 8]
As we have said this can get a little confusing with numbers as the items in the array sometimes, so you could say
const numbers = [1, 2, 3, 4, 5];
const numbersToAppend = [7, 8];
numbers.splice(3, 2, ...numbersToAppend);
console.log(numbers); // result: [1, 2, 3, 7, 8]
So what this means is that we can change multiple items at a go with this method. Awesome.
Alright so these are great ways to modify an array, so you've learned to replace or change an array, add multiple items and single items to an array, and removing single items and multiple items from an array. That's a lot. Kudos.
Copying an Array
Now there is a common method that is used in arrays, it doesn't actually change the array but it slices a part of an array to form its own array. Like borrowing, only that it's not gonna payback.
const numbers = [1, 2, 3, 4, 5];
const newNumbers = numbers.slice(1, 4);
console.log(newNumbers); // result: [2, 3, 4]
console.log(numbers); // result: [1, 2, 3, 4, 5]
Another word you can use for it is stealing, or more interestingly copying. So with this method, we can copy an array, before I explain that, let us first look and understand the syntax.
The slice method takes two arguments, the first being the start position(index) and the last being the end position(index). The end position is not included, while the first is included.
const cars = ['Ford', 'BMW', 'Mercedes', 'Honda'];
const expensiveCars = cars.slice(1, 3);
console.log(expensiveCars); // result: ['BMW', 'Mercedes']
console.log(cars); // result: ['Ford', 'BMW', 'Mercedes', 'Honda']
We can use this method to copy an array into another array without referencing.
const cars = ['Ford', 'BMW', 'Mercedes', 'Honda'];
const clonedCars = cars.slice(0);
// changes from this line on the cars array will not affect the clonedCars array e.g
cars.push('Toyota');
console.log(clonedCars); // result: ['Ford', 'BMW', 'Mercedes', 'Honda']
console.log(cars); // result: ['Ford', 'BMW', 'Mercedes', 'Honda', 'Toyota']
What this means is that changes to the cars
array after the slice()
method has been used, will not affect the clonedCars
array.
This is not the case for this
const cars = ['Ford', 'BMW', 'Mercedes', 'Honda'];
const clonedCars = cars;
// changes from this line on the cars array will affect the clonedCars array and vice versa e.g
cars.push('Toyota');
console.log(clonedCars); // result: ['Ford', 'BMW', 'Mercedes', 'Honda', 'Toyota']
console.log(cars); // result: ['Ford', 'BMW', 'Mercedes', 'Honda', 'Toyota']
You see. There is one other way to copy arrays without referencing, by using the spread operator
const cars = ['Ford', 'BMW', 'Mercedes', 'Honda'];
const clonedCars = [...cars];
// changes from this line on the cars array will not affect the clonedCars array e.g
cars.push('Toyota');
console.log(clonedCars); // result: ['Ford', 'BMW', 'Mercedes', 'Honda']
console.log(cars); // result: ['Ford', 'BMW', 'Mercedes', 'Honda', 'Toyota']
Just like how the splice method works.
Sorting Arrays
Sorting an array in JavaScript is very easy. We make use of the sort()
method to sort an array. Sorting an array can be done alphabetically or numerically depending on the items on the array.
Sort Arrays Alphabetically.
Say we have a list of names, and we want to sort them alphabetically, we can use the sort()
method on that list to sort it alphabetically I.e A - Z.
const names = ['John', 'Sarah', 'Micheal', 'Brad', 'Faith', 'Anthony'];
names.sort();
console.log(names); // result: [ 'Anthony', 'Brad', 'Faith', 'John', 'Micheal', 'Sarah' ]
Note: The sort
method changes the original array to the sorted array just as it returns the sorted array as its value
const names = ['John', 'Sarah', 'Micheal', 'Brad', 'Faith', 'Anthony'];
const sortedNames = names.sort();
console.log(sortedNames); // result: [ 'Anthony', 'Brad', 'Faith', 'John', 'Micheal', 'Sarah' ]
console.log(names); // result: [ 'Anthony', 'Brad', 'Faith', 'John', 'Micheal', 'Sarah' ]
If you don't want to change the original array, then you can make a copy of that array and sort the cloned array. That means copying without referencing. This has been explained previously in this article.
const names = ['John', 'Sarah', 'Micheal', 'Brad', 'Faith', 'Anthony'];
const sortedNames = [...names];
sortedNames.sort();
console.log(sortedNames); // result: [ 'Anthony', 'Brad', 'Faith', 'John', 'Micheal', 'Sarah' ]
console.log(names); // result: [ 'John', 'Sarah', 'Micheal', 'Brad', 'Faith', 'Anthony' ]
Sort Arrays Numerically
A group of numbers can also be sorted in JavaScript as in ascending or descending order.
Sorting Numbers In Ascending Order
Ascending would mean from 1 to greater than 1 (1, 2, 3, 4, n > 1). JavaScript sorts numbers by using a compare function. It's as easy as comparing two numbers to determine who is bigger.
Here is a metaphor, say you're a teacher how would you sort your students in ascending order? You simply look at the first and say hold up, look at the second compare with the first; whoever is shorter is sent to the beginning. You will do this continually till you get to the last person.
How exactly does JavaScript do it?
The compare function compares two numbers and usually return negative, zero or positive value.
function compare(a, b) {
return a - b;
} // ascending
If we passed 5 and 10 respectively as arguments for the compare
function, it will return a negative value. And so because it returned a negative value we can say, the second (10) is greater than the first (5).
If we inverse the order and pass 10 and 5 respectively as the arguments of the compare
function, it will return a positive value indicating the first (10) is greater than the last (5).
If the values are equal, it will return zero, indicating equality.
The compare
function is passed as a callback function to the sort()
method which in turn sends values to the compare
function, and then does the arrangement based on the returned values from the function (negative, zero, or positive).
const numbers = [2, 4, 1, 90, 3, 9, 5, 101];
function compare(a, b) {
return a - b;
} // ascending
numbers.sort(compare);
console.log(numbers); // result: [ 1, 2, 3, 4, 5, 9, 90, 101 ]
Using the arrow function makes it more readable
const numbers = [2, 4, 1, 90, 3, 9, 5, 101];
numbers.sort((a, b) => a - b);
console.log(numbers); // result: [ 1, 2, 3, 4, 5, 9, 90, 101 ]
Sort Numbers in Descending order
Same as ascending order, only that the compare function will change. This time the first value needs to be subtracted from the second value to return negative, zero, or positive values.
const numbers = [2, 4, 1, 90, 3, 9, 5, 101];
numbers.sort((a, b) => b - a); // descending
console.log(numbers); // result: [ 101, 90, 9, 5, 4, 3, 2, 1 ]
Can we sort numbers in strings?
While this is not recommended, it is worthy of note that JavaScript is smart enough to sort numbers in strings in ascending or descending order. As long as these numbers are not mixed with other characters. Other characters except for the period character (.).
const numbers = ['2.22', '4', '1.90', '90', '3', '9', '5', '10.1'];
numbers.sort((a, b) => b - a); // descending
console.log(numbers); // result: [ '90', '10.1', '9', '5', '4', '3', '2.22', '1.90' ]
Using other characters with it will provide you the outcome you are not expecting. When mixed with other characters, 9 will be greater than 200 because 9 is greater than 2. So JavaScript will be confused.
const numbers = ['2.22', '4', '10Q', '90L', '3P', '9', '5', '10.1'];
numbers.sort((a, b) => b - a); // descending
console.log(numbers); // result: [ '4', '2.22', '10Q', '90L', '3P', '10.1', '9', '5' ]
The ultimate course to JavaScript debugging. Learn How to Debug JavaScript Errors
JavaScript Array Loops.
To interact with each item in an array or maybe change each item in an array we simply loop through the array. As a web developer, you will always loop through arrays, as long as you keep using arrays. You cannot run away from it.
There are several cool ways to loop through arrays in JavaScript, one of which is using the JavaScript higher-order array methods.
These higher-order array methods can loop through an array and make changes or simply return a value based on some conditions. We will not be looking at every one of them, but we will be looking at the ones you will often find yourself in need of.
Changing or Reading each item in an array.
The following methods can be comfortably and suitably used to modify or read each item in an array.
The forEach()
method
The forEach()
method is an array method that can execute a function for each item in an array.
The forEach()
method takes a callback function, and this function can take up to three parameters. The first parameter represents each item in the array, the second parameter represents the index of each item in the array, and the third parameter represents the array you are looping. The second and third are optional.
const numbers = [3, 4, 1, 3];
numbers.forEach((number, index) => {
console.log(number + index);
});
You should note that the forEach()
method returns undefined as its value. So when can I use the forEach()
method? Say you have a very complex array with objects that represents a user. Assuming you are to create an HTML element for each user in the array, you could say
const users = [
{
username: 'johndoe_4real',
email: 'johndoe@gmail.com',
},
{
username: 'spacex_elon',
email: 'elonmusk@spacex.com',
},
{
username: 'therock',
email: 'therock@wwe.com',
},
];
function createListElement(user) {
const li = document.createElement('li');
li.innerHTML = `
<h2>I am ${user.username}</h2>
<p>Contact me via ${user.email}
`;
ul.appendChild(li);
}
users.forEach((user) => {
createListElement(user);
});
So for each item, our forEach()
method will call a function that creates an <li>
element.
The map()
method
Just like the forEach()
method and apparently every other higher-order array method, the map()
method takes in a callback function as an argument. This function takes three parameters. The first parameter represents each item in the array, the second represents the index of each item, and the third represents the array being looped.
const numbers = [1, 2, 3, 4, 5];
numbers.map((number, index) => {
console.log(number + index);
});
The map()
method is one of the most used higher-order array methods. Very similar to the forEach()
method. The difference is while a forEach()
method cannot return a value, a map()
method gladly returns an array as its value.
Say we wanted to print the result of the code above as a new array, using forEach()
would be
const numbers = [1, 2, 3, 4, 5];
const newNumbers = [];
numbers.forEach((number, index) => {
newNumbers.push(number + index);
});
console.log(newNumbers); // result: [1, 3, 5, 7, 9]
But with the map method, it is way easier
const numbers = [1, 2, 3, 4, 5];
const newNumbers = numbers.map((number, index) => {
return number + index;
});
console.log(newNumbers); // result: [1, 3, 5, 7, 9]
Though it is easier, it is more than 60% slower than the first example with the forEach()
method. So make your choice.
The filter()
method
The filter()
method returns an array of each item in an array that passes a test. It takes a callback function with three parameters just as the above in map()
and forEach()
.
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const newNumbers = numbers.filter((number) => {
return number > 5;
});
console.log(newNumbers); // result: [6, 7, 8, 9, 10]
Simply put, the filter()
method filters a group of elements from an array and returns a new array containing these items. Say you have a very complex array of objects representing a user. So here we are with a bunch of users, if we wish to get all the admins in this array we would say
const users = [
{ name: 'Jerry', age: 20, isAdmin: false },
{ name: 'Brad', age: 22, isAdmin: false },
{ name: 'Jennifer', age: 19, isAdmin: true },
{ name: 'Simon', age: 20, isAdmin: false },
{ name: 'Rajash', age: 24, isAdmin: true },
];
const admins = users.filter((user) => {
return user.isAdmin;
});
console.log(admins);
/* result: [ { name: 'Jennifer', age: 19, isAdmin: true },
{ name: 'Rajash', age: 24, isAdmin: true } ]
*/
The code inside the callback function will check for each item if isAdmin
is true. The filter()
method is one of the methods you will always find yourself using when working with arrays in JavaScript.
There is almost another method that is similar to the filter method is the find method.
Hey there, I figured you might be interested in learning Asynchronous Javascript.
The find()
method
The find()
method though not supported in older browsers can serve as a good way to get a unique item from a list. The find()
method loops through an array to return the first item of that array that passes a test or condition.
It takes a callback function which in turn takes three parameters as mentioned before in the map()
and forEach()
methods.
const users = [
{ name: 'Jerry', age: 20, isAdmin: false },
{ name: 'Brad', age: 22, isAdmin: false },
{ name: 'Jennifer', age: 19, isAdmin: true },
{ name: 'Simon', age: 20, isAdmin: false },
{ name: 'Rajash', age: 24, isAdmin: true },
];
const anAdmin = users.find((user) => {
return user.isAdmin;
});
console.log(anAdmin); // result: { name: 'Jennifer', age: 19, isAdmin: true }
It is quite similar to the filter()
method in returning unique items in an array. For example, we have a class of students, and in this class, there is only one girl; we could use the filter()
method to return the girl thus
const students = [
{ name: 'Jerry', age: 20, gender: 'male' },
{ name: 'Brad', age: 22, gender: 'male' },
{ name: 'Jennifer', age: 19, gender: 'female' },
{ name: 'Simon', age: 20, gender: 'male' },
{ name: 'Rajash', age: 24, gender: 'male' },
];
const onlyGirl = students.filter((student) => {
return student.gender === 'female';
});
console.log(onlyGirl); // result: [ { name: 'Jennifer', age: 19, gender: 'female' } ]
We can also perform the same function using the find()
method thus
const students = [
{ name: 'Jerry', age: 20, gender: 'male' },
{ name: 'Brad', age: 22, gender: 'male' },
{ name: 'Jennifer', age: 19, gender: 'female' },
{ name: 'Simon', age: 20, gender: 'male' },
{ name: 'Rajash', age: 24, gender: 'male' },
];
const onlyGirl = students.find((student) => {
return student.gender === 'female';
});
console.log(onlyGirl); // result: { name: 'Jennifer', age: 19, gender: 'female' }
You should note that the find()
method is 78.1% slower than the filter()
method in the operation above.
It can also be useful in getting one of many other items. Again say we have a class of students, and in this class, there are 20 girls. If we want to get any girl (doesn't matter who, just any girl), we could use the find()
method.
But when we want to get all the girls then using the filter()
method is our best option, because obviously find()
is not going to get us what we want here.
There are other higher-order array methods that are used with conditionals like the
-
every()
method - checks if all the items in an array pass a test or condition; returns a Boolean as its value, -
some()
method - checks if some of the items in an array pass a test or condition; returns a Boolean as its value, and -
findIndex()
method - returns the index of the first array that passes a test or condition.
These three are not popular because they are not always used, but it is good for you to know them, it may come in handy someday.
So these are the higher-order array methods commonly used for looping arrays. You can also use the for loop or while loop to iterate an array. All of the examples above can be done with a for loop or while loop.
But not too many developers don't use the for loop for JavaScript arrays, they prefer using the array methods. Probably because of the readability and complexity. But the truth is the for loop is faster than these array methods when performing their job.
There are times it is 72% faster and there are times when it is slightly faster depending on the complexity of the task to be done. The more the complexity, the faster it is.
Let's practically try this out.
The last example we made mention of above is getting all the girls in a class of students, I am going to use the forEach()
method, the filter()
method, and then a for a loop. And we will run these codes in jsbench and see which is fastest.
Our global array
const students = [
{ name: 'Jerry', age: 20, gender: 'male' },
{ name: 'Brad', age: 22, gender: 'male' },
{ name: 'Jennifer', age: 19, gender: 'female' },
{ name: 'Simon', age: 20, gender: 'male' },
{ name: 'Sandra', age: 24, gender: 'female' },
];
Using foreach
const allGirls = [];
students.forEach((student) => {
if (student.gender === 'female') {
allGirls.push(student);
}
});
console.log(allGirls);
Using filter
const allGirls = students.filter((student) => {
return student.gender === 'female';
});
console.log(allGirls);
Using for loop
const allGirls = [];
for (let i = 0; i < students.length; i++) {
if (students[i].gender === 'female') {
allGirls.push(students[i]);
}
}
console.log(allGirls);
Am not sure if you can see that screenshot, because I can't see anything. Nonetheless, you can just copy the code and try it out on jsbench.me. But from what I tested the for loop was fastest, followed by the forEach and then then the filter method.
Conclusion
Alright, my fellow programmers, this is where I will draw the curtain on arrays. There are so many beautiful things about an array just as there are in JavaScript. If you want to learn more JavaScript, or more array methods and properties you can check out the Codecademy course.
With Codecademy you can also build projects and see how these things work in real-world applications.
Please if you like people this article, you can kindly like, comment, and share it with your fellow programmers. You can also subscribe to my newsletter to get updates when I make new posts. You can buy me coffee to support my blogging.
Don't also forget to..., no that's fine, I feel like I have asked too much from you :). You've done a lot. Thanks. Happy hacking and learning. See you next time.
Top comments (5)
Great tool, but you really don't need it all the time, the array methods that mutate the original array has been kept under the "Modifying an Array" Section.
Also from my experience, I have always changed the original array with the push method in production, it has always end up being a solution without causing effect,. I have also seen it mutating the array in source. But you did make a point there which I understand.
Then for the test, I totally agree with you, I use the filter or forEach keyword myself. But for now I am doing a lot of research on speed test. Something that I noticed that I should drop here is this, the speed of the for loop was not because of the
for
loopz but because of the mathematics used in constructing the for loop. The same is not the case for afor in
loop.Thanks for the comment.
That was really great!! I have learnt alot.
Thank you for the post.
You are welcome.
good read!
thanks a lot