21
loading...
This website collects cookies to deliver better user experience
const studentNames = [
'Dwayne Johnson',
'Lionel Messi',
'Kevin Hart',
'Elon Musk',
'Lebron James',
];
studentNames
represents the names of students in a class. Each student's name can be referred to as an item or element or member.studentNames[0]; // returns 'Dwayne Johnson
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]
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.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]
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]
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.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']
const languages = ['Python', 'Javascript', 'Java', 'Go'];
languages.splice(2, 0, 'PHP', 'C++', 'C#');
console.log(languages); // result: ['Python', 'Javascript', 'PHP', 'C++', 'C#', Java', 'Go']
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]
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]
const numbers = [1, 2, 3, 4, 5];
numbers[7] = 8;
console.log(numbers); // result: [1, 2, 3, 4, 5, undefined, undefined, 8]
const numbers = [1, 2, 3, 4, 5];
numbers[numbers.length] = 6;
console.log(numbers); // result: [1, 2, 3, 4, 5, 6]
numbers.length
, then we set it as an index for a new item.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]
delete
keyword which would have been my favorite is the one you should never use.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.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
shift()
will remove the first item in an array. It usually returns the removed item as its value.const numbers = [1, 2, 3, 4, 5];
const removedNum = numbers.shift();
console.log(numbers); // result: [2, 3, 4, 5]
console.log(removedNum); // result: 1
const numbers = [1, 2, 3, 4, 5];
numbers.splice(4, 1);
console.log(numbers); // result: [1, 2, 3, 4]
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]
const numbers = [1, 2, 3, 4, 5];
numbers.length = numbers.length - 1;
console.log(numbers); // result: [1, 2, 3, 4]
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']
const numbers = [1, 2, 3, 4, 5];
numbers[2] = 25;
console.log(numbers); // result: [1, 2, 25, 4, 5]
indexOf()
method.const numbers = [1, 2, 3, 4, 5];
console.log(numbers.indexOf(3)); // result: 2
splice()
method, we can also replace or change items in an array with it. Here is howconst 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]
const numbers = [1, 2, 3, 4, 5];
numbers.splice(3, 2, 7, 8);
console.log(numbers); // result: [1, 2, 3, 7, 8]
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]
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]
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']
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']
cars
array after the slice()
method has been used, will not affect the clonedCars
array.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']
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']
sort()
method to sort an array. Sorting an array can be done alphabetically or numerically depending on the items on the array.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' ]
sort
method changes the original array to the sorted array just as it returns the sorted array as its valueconst 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' ]
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' ]
function compare(a, b) {
return a - b;
} // ascending
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).compare
function, it will return a positive value indicating the first (10) is greater than the last (5).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 ]
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 ]
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 ]
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' ]
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' ]
forEach()
method is an array method that can execute a function for each item in an array.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);
});
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 sayconst users = [
{
username: 'johndoe_4real',
email: '[email protected]',
},
{
username: 'spacex_elon',
email: '[email protected]',
},
{
username: 'therock',
email: '[email protected]',
},
];
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);
});
forEach()
method will call a function that creates an <li>
element.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);
});
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.forEach()
would beconst 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]
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]
forEach()
method. So make your choice.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]
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 sayconst 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 } ]
*/
isAdmin
is true. The filter()
method is one of the methods you will always find yourself using when working with arrays in JavaScript.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.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 }
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 thusconst 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' } ]
find()
method thusconst 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' }
find()
method is 78.1% slower than the filter()
method in the operation above.find()
method.filter()
method is our best option, because obviously find()
is not going to get us what we want here.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, andfindIndex()
method - returns the index of the first array that passes a test or condition.forEach()
method, the filter()
method, and then a for a loop. And we will run these codes in jsbench and see which is fastest.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' },
];
const allGirls = [];
students.forEach((student) => {
if (student.gender === 'female') {
allGirls.push(student);
}
});
console.log(allGirls);
const allGirls = students.filter((student) => {
return student.gender === 'female';
});
console.log(allGirls);
const allGirls = [];
for (let i = 0; i < students.length; i++) {
if (students[i].gender === 'female') {
allGirls.push(students[i]);
}
}
console.log(allGirls);