Array and Array Methods in JavaScript
Hi, have you ever wondered why airplanes, theatres or buses have consecutive numbers as their seating numbers? Well first sensible answer comes to mind is that it makes easy to find the seats. But in addition to easy identification, seating becomes more systematic and organized while taking minimum possible space.
Array
Arrays have similar approach behind it. Programmer when dealing with multiple variables, put them in a single group which can be later used and perform operations on them.
Definition
Technically, Array enables storing a collection of multiple items under a single variable name, and has members for performing common array operations.
Example
Most common way in JavaScript to create an array is
let animals = ['cat', 'dog', 'hamster'];
Here, an array named animals is created which have 3 elements cat, dog, hamster. as for numbering of the imaginary consecutive seating for animal name in the memory location, we call those numbers as index and it instead of 1 it starts with 0. therefore cat is at 0 index, dog is at 1 and hamster is at 2.
console.log(animals[0]); // expected output: 'cat'
console.log(animals[1]); // expected output: 'dog'
console.log(animals[2]); // expected output: 'hamster'
Array Methods
An Array being a mostly use data structure might be easy to use and understand when it contains three elements but it can be a nightmare when handling tens of thousands of elements. So, just to make your life simpler we have methods to process and manipulate the array. It should be noted that unlike c or c++, we can have elements of different datatype for examples:
let arrayInJavaScript = [ 232,420,true,"New york", "central park"]
is a valid array in Javascript
we have a lot of array methods available in JavaScript . I am going to cover mostly used methods in this article.
- at()
- concat()
- every()
- find()
- filter()
- foreach()
- includes()
- indexof()
- map()
- of()
- pop()
- push()
- sort()
- splice()
- shift()
- tostring()
at()
at() method takes a index as parameter and returns the element present at that index.
animals.at(1); //expected output: 'dog'
concat()
The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
const animals = ['mouse', 'cat', 'dog'];
const colors = ['red', 'blue', 'green'];
const animalsAndColors = animals.concat(colors);
console.log(animalsAndColors);
// expected output: Array ['mouse', 'cat', 'dog', 'red', 'blue', 'green']
NOTE: callback functions are those function which either takes another function as parameters or returns a function
every()
The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value(i.e. true/false).
const checklessthanforty = (currentValue) => currentValue < 40;
const numbers = [1, 30, 39, 29, 10, 13];
console.log(array1.every(checklessthanforty));
// expected output: true
find()
The find() method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
const numbers = [5, 12, 8, 130, 44];
const found = numbers.find(element => element > 10);
console.log(found);
// expected output: 12
filter()
The filter() method creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
foreach()
The forEach() method executes a provided function once for each array element.
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
// expected output: "a"
// expected output: "b"
// expected output: "c"
includes()
The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat'));
// expected output: true
console.log(pets.includes('at'));
// expected output: false
indexof()
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// expected output: 1
// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4
console.log(beasts.indexOf('giraffe'));
// expected output: -1
map()
The map() method creates a new array populated with the results of calling a provided function on every element in the array.
const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]
of()
The Array.of() method creates a new Array having elements passed as an arguments
Array.of(7); // [7]
pop()
The pop() method removes the last element from an array and returns that element.
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
console.log(plants.pop());
// expected output: "tomato"
console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]
push()
The push() method adds one or more elements to the end of an array and returns the new length of the array.
const animals = ['pigs', 'goats', 'sheep'];
const count = animals.push('cows');
console.log(count);
// expected output: 4
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows"]
sort()
as name suggests sort() function is use to sort the array and it return the reference pf same array now sorted
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]
splice()
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]
shift()
The shift() method removes the first element from an array and returns that removed element.
const array1 = [1, 2, 3];
const firstElement = array1.shift();
console.log(array1);
// expected output: Array [2, 3]
console.log(firstElement);
// expected output: 1
toString()
The JavaScript method toString()
converts an array to a string of (comma separated) array values.
animals.toString(); //expected output: 'cat,dog,hamster'
Hope you find this article helpful. Happy coding