Javascript - Arrays and it's methods

Javascript - Arrays and it's methods

(The Ultimate reference)

Javascript - Arrays.gif

Introduction-

Arrays - we all have heard about them. These are the one of the first and most loved data structures used by coders around the world. It's operations are one of the simplest and that's why it is one of the easiest to learn in a programming journey.

Javascript also provides us these boon of array data structures with its own unique blend of super powers. In javascript , arrays possess certain properties which can be used to perform various operations on them to exact various information. In fact Javascript treats these arrays as if they are some sort of objects !. Interesting, isn't it? So let's dive into these unique superpower/features of arrays in Javascript to learn about some of these.

Arrays in Javascript-

Arrays in Javascript are usually declared by using "[]" notation. They can be also be declared using the new keyword (Array Object constructor).

1. Using "[]" :
    let arr = ["A", 1, 25, "#",{a:12}];

2. Using new keyword:
    let arr = new Array("A", 1, 25, "#",{a:12});

One unique feature of arrays in Javascript is that they can store different types of values unlike many programming languages. Otherwise all the other features are same, e.g.- elements are separated by "," and it behaves like a list of elements.

Arrays-hashnode.jpg

Position of an element in an array can be accessed using an index. The index is nothing but a number that denotes the position of that element in the array. In the programming world counting the position of an element in an array starts from 0 and the position of the last element is (size of array)-1.

Access elements of an array

To access an individual element from an array, the index of that element can be used.

  let grocery = ["bread", "milk", "eggs", "chips"];
  let milk=  grocery[1];
  console.log(milk);

  /* Output is "milk" */

Remember index in an array starts from 0, so to access "milk" from the array above we need to give the index as 1.

We can replace or modify an element of an array by using the index of that element. Let's replace "chips" with "coffee". We know the index of "chips" so we can replace it as shown in the example below.

let grocery = ["bread", "milk", "eggs", "chips"];
grocery[3] = "coffee";
console.log(grocery);
Output
 ["bread", "milk", "eggs", "coffee"]

Size of an Array

To get the size of an array we can use .length property. This returns the number of elements present in (or size of) the array.

let items = ["a", "b", "c", "d"];
let size = items.length;
console.log(size);
Output
4

length is a property and not a function, hence we should not to use () for ex- .length() or it will throw you an error.

Array Methods -

1. push() -

Adds a new element at the end of an array and returns the size of the updated array. Syntax - push(element).

Syntax -

push(element0)
push(element0, element1)
push(element0, element1, /* … ,*/ elementN)

Returns - the size of the updated array

Example

let nos = [10, 20, 30, 40];
let updatedLen = nos.push(50);
console.log(updatedLen);
console.log(nos);
Output-
5
[10, 20, 30, 40, 50 ]

2. pop() -

Removes an element from the end of an array and returns the deleted element. So using pop() on our nos list will delete the last item from the list.

Syntax - array.pop()

Returns - The removed element from the array; undefined if the array is empty.

Example -

let nos = [10, 20, 30, 40];
let deletedEl = nos.push(50);
console.log(deletedEl);
console.log(nos);
Output-
50
[10, 20, 30, 40 ]

3. shift() -

Removes an element from the first of an array and returns the deleted element and shifts all the remaining elements to the left. So using shift() on our nos list will delete the first item from the list.

Returns - The removed element from the array; undefined if the array is empty.

Example -

let nos = [10, 20, 30, 40];
let deletedEl = nos.shift(10);
console.log(deletedEl);
console.log(nos);
Output-
10
[20, 30, 40 ]

arrays-shift.jpg array-shift1.jpg

4. unshift() -

Adds one or more elements to the start of an array and returns new length of the array. It shifts existing elements to the right and adds new elements at the start, hence it changes the index of all elements in the array. Using this method is not suggested when the size of array is large as its a heavy operation because each element has to be shifted in the array. Therefore, use push().

Syntax- unshift(ele1, ele2, ele3,....ele4).

let nos = [10, 20, 30, 40];
let newlen = nos.unshift(10);
console.log(newlen);
console.log(nos);
Output-
5
[10,20, 30, 40 ]

image.png

image.png

5. concat()-

Merges two or more arrays. This method does not change the existing arrays, but instead returns a new array.

Syntax- `concat(value0, value1)

Parameters - arr1,arr2,....,arrn . It represent the arrays to be combined.

Returns - A new Array instance.

let grocery = ["bread", "milk", "eggs", "chips"];
let newGrocery = ["butter", "yoghurt", "almonds"];
let updatedList = grocery.concat(newGrocery);
console.log(updatedList);
Ouput
[
  'bread',   'milk',
  'eggs',    'chips',
  'butter',  'yoghurt',
  'almonds'
]

6. slice()-

Returns a portion of an existing array as a new array. It doesn't modify the existing array.

Requires start and end indexes as arguments where start is the starting index of required group of elements and end is the ending index of element which is next to the last element of required group of elements. This means that the element at the ending index will not be included.

When only starting index is provided as an argument, it returns a group of elements starting from starting index to the end of the array. And if no argument is passed, it returns whole array.

Syntax- slice() slice(start) slice(start,end)

Parameters -

start - It is optional. It represents the index from where the method starts to extract the elements.

  • A negative index can be used, indicating an offset from the end of the sequence. Ex- slice(-2) extracts the last two elements in the sequence.
  • If start is undefined, slice starts from the index 0.
  • If start is greater than the index range of the sequence, an empty array is returned.

end - It is optional. It represents the index at where the method stops extracting elements.For example, slice(1,4) extracts the second element through the fourth element

  • A negative index can be used, indicating an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence.
  • If end is omitted, slice extracts through the end of the sequence (arr.length).
  • If end is greater than the length of the sequence, slice extracts through to the end of the sequence (arr.length).

Example-

let grocery = ["bread", "milk", "eggs", "chips", "butter", "yoghurt", "almonds"];

// values from 1 to 3
let slicedList = grocery.slice(1,4);
console.log(slicedList);

// values from 4 to end of array
let slicedList2 = grocery.slice(4);
console.log(slicedList2);
Output
[ 'milk', 'eggs', 'chips' ]
[ 'butter', 'yoghurt', 'almonds' ]

7. splice() -

Modifies existing array by deleting or replacing existing elements or by adding new elements. Returns an array containing the deleted elements.

Syntax-

splice(start)
splice(start, deleteCount)
splice(start, deleteCount, element1)
splice(start, deleteCount, element1, element2,.... elementN)

start parameter denotes the index at which modification of array should start.

deleteCount parameter denotes number of elements to be removed from start.

element1, ......, elementN denotes elements to be added from start.

Returns - A new array containing the removed elements.

Example -

let items = ["bread", "butter", "cottage cheese"];

//adds coffee at position 1 and deletes 0 elements
items.splice(1, 0, "coffee");
console.log(items);
//output - [ 'bread', 'coffee', 'butter', 'cottage cheese']

// deletes 1 element from index 2 and adds 2 elements from index 2 
items.splice(2, 1, "tea", "curd")
console.log(items);
//output - [ 'bread', 'coffee', 'tea', 'curd', 'cottage cheese' ]

// remove all elements from index 1
items.splice(1);
console.log(items);
//output - [ 'bread' ]

8. toString() -

The toString() method is used for converting and representing an array into string form and returns a string with array values separated by ','. The toString() method does not change the original array.

Note - Every JavaScript object has a toString() method. The toString() method is used internally by JavaScript when an object needs to be displayed as a text (like in HTML), or when an object needs to be used as a string.

Syntax - array.toString()

Returns - A string representing the object.

const array1 = [1, 2, 'a', '1a'];
console.log(array1.toString());
// expected output: "1,2,a,1a"

9. join() -

This method creates and returns a new string by concatenating all of the elements in an array, separated by ',''s or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

Parameters - Separator() - It is optional. It represent the separator used between array elements.

Return value - If arr.length is 0, the empty string is returned.

Syntax -

join()
join(separator)

Example-

const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// expected output: "Fire,Air,Water"

console.log(elements.join(''));
// expected output: "FireAirWater"

console.log(elements.join('-'));
// expected output: "Fire-Air-Water"

10. reverse() -

It reverses an array in place and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously shown.

Syntax - array.reverse()

Return value - The reference to the original array, now reversed.

Example -

const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// expected output: "array1:" Array ["one", "two", "three"]

const reversed = array1.reverse();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]

// Careful: reverse changes the original array.
console.log(array1);
// expected output: Array ["three", "two", "one"]

11. sort() -

The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, done upon converting the elements into strings.

Parameters :

(compareFn) - Takes a function that defines the sort order. If not provided, the array elements are converted to strings, then sorted according to each character's Unicode code value.

a:The first element for comparison.

b:The second element for comparison.

Return value -

The reference to the original array, now sorted.

Description - If compareFn is not supplied, all non-undefined array elements are sorted by converting them to strings and comparing strings in UTF-16 code.

If compareFn is supplied, all non-undefined array elements are sorted according to the return value of the compare function.

image.png

Examples -

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]

const numbers2 = [4, 2, 5, 1, 3];
numbers2.sort((a, b) => a - b);
console.log(numbers2);
// [1, 2, 3, 4, 5]

12. includes() -

Determines whether an array includes a certain value among its entries, and returns true or false as appropriate.

Syntax -

includes(searchElement)
includes(searchElement, fromIndex)

Parameters -

searchElement - The value to search for.

fromIndex - The position in this array at which to begin searching for searchElement. The first element to be searched is found at fromIndex for positive values of fromIndex, or at arr.length + fromIndex for negative values of fromIndex.

Returns true if the value searchElement is found within the array, else false.

Examples-

[1, 2, 3].includes(2)         // true
[1, 2, 3].includes(4)         // false
[1, 2, 3].includes(3, 3)      // false
[1, 2, 3].includes(3, -1)     // true
[1, 2, NaN].includes(NaN)     // true
["1", "2", "3"].includes(3)   // false

13. indexOf() -

Returns the position of the first occurrence of a value in the array. If the value cannot be found, -1 is returned. This method has two parameters the item we want to search and the position from where we want to start the search in the start. If only a single parameter is passed it will be treated as the element to search and it will be searched from the start of the array.

Parameters -

searchElement - The value to search for.

fromIndex - The index to start the search at. If the index is greater than or equal to the array's length, -1 is returned, which means the array will not be searched. If the provided index value is a negative number, it is taken as the offset from the end of the array

Syntax -

indexOf(searchElement)
indexOf(searchElement, fromIndex)

Examples -

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

const array = [2, 9, 9];
console.log(array.indexOf(7));     // -1
console.log(array.indexOf(9, 2));  // 2
console.log(array.indexOf(2, -1)); // -1
console.log(array.indexOf(2, -3)); // 0

14. copyWithin() -

This method copies (shallow copies) part of an array to another location in the same array and returns it without modifying its length.

Syntax -

copyWithin(target)
copyWithin(target, start)
copyWithin(target, start, end)

Parameters -

target - Zero-based index at which to copy the sequence to. If negative, target will be counted from the end. If target is at or greater than arr.length, nothing will be copied. If target is positioned after start, the copied sequence will be trimmed to fit arr.length.

start (Optional) - Zero-based index at which to start copying elements from. If negative, start will be counted from the end. If start is omitted, copyWithin will copy from index 0.

end (Optional) - Zero-based index at which to end copying elements to. copyWithin copies up to but not including end. If negative, end will be counted from the end. If end is omitted, copyWithin will copy until the last index (default to arr.length).

Examples -

console.log([1, 2, 3, 4, 5].copyWithin(-2));
// [1, 2, 3, 1, 2]

console.log([1, 2, 3, 4, 5].copyWithin(0, 3));
// [4, 5, 3, 4, 5]

console.log([1, 2, 3, 4, 5].copyWithin(0, 3, 4));
// [4, 2, 3, 4, 5]

console.log([1, 2, 3, 4, 5].copyWithin(-2, -3, -1));
// [1, 2, 3, 3, 4]

15. find() -

Returns the first element found from the array which satisfies the given condition. Takes a callback function as an argument that executes on each value in the array.If no values satisfy the testing function, undefined is returned.

Syntax -

array.find(callback(value,index,arr),thisArg)

Parameters -

callback - It represents the function that executes each element.

value - The current element of an array.

index - It is optional. The index of current element.

arr - It is optional. The array on which find() operated.

thisArg - It is optional. The value to use as this while executing callback

Returns - The value of first element of the array that satisfies the function condition.

Examples -

const inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
];

function isCherries(fruit) {
  return fruit.name === 'cherries';
}
console.log(inventory.find(isCherries));
// { name: 'cherries', quantity: 5 }

//Using arrow function and destructuring
const inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
];
const result = inventory.find(({ name }) => name === 'cherries');
console.log(result) // { name: 'cherries', quantity: 5 }

16. findIndex() -

The findIndex() method returns the index of the element that satisfies a testing function or -1 if no element passed the test.

Syntax -

array.findIndex(callback(value,index,arr),thisArg)

Parameters -

callback - It represents the function that executes each element.

value - The current element of an array.

index - It is optional. The index of current element.

arr - It is optional. The array on which findIndex() method operated.

thisArg - It is optional. The value to use as this while executing callback.

Returns - The index of first element of the array that satisfies the function condition.

Examples -

const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber));
// expected output: 3

17. every() -

This method checks whether all the given elements of an array are satisfying the provided condition and returns true when each given array element satisfies the condition otherwise false. It does not execute the function for empty elements and does not modify the original array.

Syntax -

array.every(function(currentValue, index, arr), thisValue)

Parameters -

function() (Required) - A function to be run for each element in the array.

currentValue (Required) - The value of the current element.

index (Optional) - The index of the current element.

arr (Optional) - The array of the current element.

Returns - true if the callbackFn function returns a truthy value for every array element. Otherwise, false.

Examples -

function isBigEnough(element, index, array) {
  return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough);   // false
[12, 54, 18, 130, 44].every(isBigEnough); // true

[12, 5, 8, 130, 44].every((x) => x >= 10);   // false
[12, 54, 18, 130, 44].every((x) => x >= 10); // true

18. some() -

Tests whether at least one element in the array satisfies the condition or not. Returns true if at least one element matches the condition and false if none of the elements satisfy the condition.

Syntax -

array.some(callback_funct(element, index, array), thisArg);

Parameters -

callback_funct: It is the function that tests each element present in the array.

It undertakes the following three arguments:

element: It is the current element, being in process.

index: Although it is optional, it is the index value of the current element in process.

arr: It is the given array on which some() method performs the test.

thisArg: It is an optional parameter, used as 'this' value while executing the callback function. If we do not provide, 'undefined' will be used as 'this' value.

Returns - true if the callback function returns a truthy value for at least one element in the array. Otherwise, false.

Examples -

//Testing values of array elements
function isBiggerThan10(element, index, array) {
  return element > 10;
}
[2, 5, 8, 1, 4].some(isBiggerThan10);  // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true

//Checking whether a value exists in an array

const fruits = ['apple', 'banana', 'mango', 'guava'];
function checkAvailability(arr, val) {
  return arr.some((arrVal) => val === arrVal);
}
checkAvailability(fruits, 'kela');   // false
checkAvailability(fruits, 'banana'); // true

19. map() -

The map() method calls the specified function for every array element and returns the new array with the results obtained from calling the specified function. This method doesn't change the original array.

Syntax -

array.map(callback(element,index,arr),thisArg)

Parameters -

callback - this is a function that is called for every element of arr. Each time callback executes, the returned value is added to newArray.

The function is called with the following arguments:

element - The current element being processed in the array.

index - The index of the current element being processed in the array.

arr - The array on which map was called.

thisArg (Optional) - Value to use as this when executing callback.

Returns - A new array with each element being the result of the callback function.

Examples -

// 1. Mapping an array of numbers to an array of square roots
const numbers = [1, 4, 9];
const roots = numbers.map((num) => Math.sqrt(num));
// roots is now     [1, 2, 3]
// numbers is still [1, 4, 9]

// 2. Using map to reformat objects in an array
const prevArray = [
  { key: 1, value: 10 },
  { key: 2, value: 20 },
  { key: 3, value: 30 },
];
const newArray = kvArray.map(({ key, value}) => ({ [key]: value }));
// newArray is now [{1: 10}, {2: 20}, {3: 30}],
// prevArray is still:
// [{key: 1, value: 10},
//  {key: 2, value: 20},
//  {key: 3, value: 30}]

// 3. Mapping an array of numbers using a function containing an argument
const numbers = [1, 4, 9];
const doubles = numbers.map((num) => num * 2);

// doubles is now   [2, 8, 18]
// numbers is still [1, 4, 9]

20. filter() -

The filter() method filters and extracts the element of an array that satisfies the provided condition. It doesn't change the original array.

Syntax -

array.filter(callback(element,index,arr),thisArg)

Parameters -

callback - This is a predicate function, to test each element of the array. Returns a value that satisfies the condition, or false otherwise.

The function is called with the following arguments:

element - The current element being processed in the array.

index - The index of the current element being processed in the array.

arr - The array on which filter() was called.

thisArg (Optional)- Value to use as this when executing callback.

Returns - a portion of the given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. If no elements pass the test, an empty array will be returned.

Examples -

// 1. Filtering out all small values
function isBigEnough(value) {
  return value >= 10;
}
const filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]

//2. Find all prime numbers in an array
const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
function isPrime(num) {
  for (let i = 2; num > i; i++) {
    if (num % i === 0) {
      return false;
    }
  }
  return num > 1;
}
console.log(array.filter(isPrime)); // [2, 3, 5, 7, 11, 13]

21. forEach() -

The forEach() method executes a provided function once for each array element.

Syntax -

array.forEach(callback(currentvalue,index,arr),thisArg)

Parameters -

callback - This is a function which executes on each element.

The function is called with the following arguments:

element - The current element being processed in the array.

index - The index of the current element being processed in the array.

arr - The array on which forEach() was called.

thisArg (Optional)- Value to use as this when executing callback.

Examples -

// 1. Converting a for loop to forEach
const items = ['item1', 'item2', 'item3'];
const copyItems = [];
// before
for (let i = 0; i < items.length; i++) {
  copyItems.push(items[i]);
}
// after
items.forEach((item) => {
  copyItems.push(item);
});

// 2. Printing the contents of an array
const logArrayElements = (element, index, array) => {
  console.log(`a[${index}] = ${element}`);
};
// Notice that index 2 is skipped, since there is no item at
// that position in the array.
[2, 5, , 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9

These are some of the most commonly used methods of arrays in javascript. There are even some more methods to explore to as there is no depth to the ocean of knowledge!

You can check these methods here :

Hope this article helped you to understand Arrays in JavaScript and its methods better. Please do like this article or put a comment to share your feedback.

Happy Coding! 💻