Javascript Arrays and their Methods and Properties

Javascript Arrays and their Methods and Properties

Defintition

In Javascript, the Arrays are collections of items of multiple data types stored at contiguous memory location.

Characteristics of JS Arrays

  1. JS arrays are resizable and can contain a mix of different data types in a single array.
  2. JS arrays are not associative arrays (these arrays are a pair of keys and values in the array form to learn more about Click here) and so these arrays are accessed using indexes.
  3. JS arrays are zero-indexed arrays. The indexing start's from zero.
  4. Whenever you try to copy arrays in JS they create shallow copies, not deep copies.

Properties

Length

To get the length of an array you can use the .length property in your array.

const arr = [1,2,3,4,5];
console.log("Arrays length is : " arr.length) // result => Arrays length is :5

Methods

array .at()

The Array .at(index_name) method gives you values at that index.

const array1 = [1,23,9,5,6];
let index = 2;

console.log(`Using an index of ${index} the item returned is ${array1.at(index)}`); 
// expected output: "Using an index of 2 the item returned is 8"

array .concat()

The Array .concat() method is used to combine more or two arrays. It doesn't change the existing array values and returns a new array.

const array1 = ['1', '2', '3'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);

console.log(array3);
// expected output: Array ["1", "2", "3", "d", "e", "f"]

array .copyWithin()

This array method helps you to copy the other items in the array and replace them. array.copyWithin(target, start, end) has three parameters target, start, and end. The first one is target means where you want to copy the element, the start and end tell you from where to where I need to copy the element if the end is not given the default is array. length.

const array1 = ['a', 'b', 'c', 'd', 'e'];

// copy to index 0 the element at index 3
console.log(array1.copyWithin(0, 3, 4));
// expected output: Array ["d", "b", "c", "d", "e"]

// copy to index 1 all elements from index 3 to the end
console.log(array1.copyWithin(1, 3));
// expected output: Array ["d", "d", "e", "d", "e"]

array .entries()

The Array. entries() methods give a new Iterator (means you can integrate it with next() method on it or use loops on it) Array Object.

const array = ["a", "b", "c"];
const arrayEntries = array.entries();

for (const element of arrayEntries) {
  console.log(element);
}

// [0, 'a']
// [1, 'b']
// [2, 'c']

array .every()

The Array. every() method tests whether the given condition is true for all the values in the array. It takes a function (it can be an arrow or callback function too) as a parameter to evaluate the test you provide in the function. If anyone returns a value that is false from the function it gives false.

const isBelowThreshold = (currentValue) => currentValue < 40;

const array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
// expected output: true

If any element in array1 is greater than 40 then it gives false.

array .fill()

The Array.fill(value, start=0,end=default.length) methods has 3 parameter value, start and end. This method fills values in the array. You need to provide which value you want to put in the array and from where to where.

const array1 = [1, 2, 3, 4];

// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]

array .find()

The Array. find() methods return the first element of the function that satisfies the condition. If their is no element that matched the condition it returns undefined. You can also give arrow or callback function.

const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);

console.log(found);
// expected output: 12

array .findIndex()

The Array .findIndex() returns the index of the first element that matches the functional condition. This is the same as find methods but instead of an element, it gives an index of that element.

const array1 = [5, 12, 8, 130, 44];

const isLargeNumber = (element) => element > 13;

console.log(array1.findIndex(isLargeNumber));
// expected output: 3

array .findLast()

The Array .findlast() returns the last element that satisfies the function condition. It's the same as the find method but gives the last element that matches the condition.

const array1 = [5, 12, 50, 130, 44];

const found = array1.findLast((element) => element > 45);

console.log(found);
// expected output: 130

array .findLastIndex()

The Array .findLastIndex() return the last element index that satisfies the functional condition. Its the same as the findIndex() methods but gives the last element index that matches the condition.

const array1 = [5, 12, 50, 130, 44];
const isLargeNumber = (element) => element > 45;

console.log(array1.findLastIndex(isLargeNumber));
// expected output: 3  (of element with value: 30)

array .flat()

flattening an array is the process of taking nested array elements and basically putting them all into one “flat” array.

The Array .flat([depth_level]) method returns a new array that flat the array elements according to the depth level of nested elements.

const arr1 = [0, 1, 2, [[[3, 4]]]];
console.log(arr1.flat(1));
// expected output: [0, 1, 2, [3, 4]]

array .flatMap()

The flatMap() method returns a new array formed by applying a given callback function to each element of the array and then flattening the result by one level. It is identical to a map() followed by a flat() of depth 1 (arr.map(...args).flat()), but slightly more efficient than calling those two methods separately.

const arr1 = [1, 2, [3], [4, 5], 6, []];
const flattened = arr1.flatMap(num => num);

console.log(flattened);
// expected output: Array [1, 2, 3, 4, 5, 6]

The flat map() method do only one level of flatting in the array.

array .forEach()

The Array .forEach() methods runs a provided function for each element in the array.

const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));

// expected output: "a"
// expected output: "b"
// expected output: "c"

array .includes()

The Array .includes() methods returns a true or false based on whether the certain values are present or not in the array.

const array1 = [1, 2, 3];

console.log(array1.includes(2));
// expected output: true

array .indexOf()

The Array .indexOf() method returns the index of given values present in the array, and if not found returns -1.

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// expected output: 1

array .join()

The Array .join(separator) method returns a new string by concatenating all the values in the array. If you provide any separator then it will separate all the elements with that separator.

const elements = ['Hitesh', 'Ayush', 'Prasad'];

console.log(elements.join());
// expected output: "Hitesh,Ayush,Prasad"

console.log(elements.join('-'));
// expected output: "Hitesh-Ayush-Prasad"

array .keys()

The Array .keys return a new Array iterator Object that contains keys for each index in the array.

const array1 = ['a', 'b', 'c'];
const iterator = array1.keys();

for (const key of iterator) {
  console.log(key);
}

// expected output: 0
// expected output: 1
// expected output: 2

array .lastIndexOf()

The Array .lastIndexOf() methods return the last index at which the given element can be found. If not found it will return -1.

const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];

console.log(animals.lastIndexOf('Dodo'));
// expected output: 3

array .map()

The Array .map() method creates a new array populated with the results of calling a provided function on every element in the calling 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]

array .pop()

The Array .pop() removes the last element from the array.

const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];

console.log(plants.pop());
// expected output: "tomato"
console.log(plants);
//expected output: ['broccoli', 'cauliflower', 'cabbage', 'kale']

array .push()

The Array .push() method adds one or more elements to the ends of the array and returns a new length for that 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"]

array .sort()

The Array .sort() method sorts the elements in that array and the sorting is done in ascending alphabetical manner.

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]

In the second example you can see that numbers are not sorted (they are sorted in string format, not a number) so to correct it you can put your own function for more details Click here

array .slice()

The Array .slice() returns a shallow copy subarray of an array selected from start to end. where start and end are parameters of slice that represent index in the array.

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

array .splice()

The Array .splice(start, deleteCount,...items) methods change the content of an array by removing or replacing and adding existing elements.

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"]

#### array .toString()
The Array .toString() method returns a string representation of that specified array.

const array1 = [1, 2, 'a', '1a'];

console.log(array1.toString()); // expected output: "1,2,a,1a"

#### array .shift()
The Array .shift() method removes the first element from the array and returns that removed the element.

const array1 = [1, 2, 3];

const firstElement = array1.shift();

console.log(array1); // expected output: Array [2, 3]

> And if no element is present then it gives undefined.

#### array .unshift()
The Array .unshift() method adds one or more elements in the front of the array. It's like shifting the elements to the end one by one and adding them to the front.

const array1 = [1, 2, 3];

console.log(array1.unshift(4, 5)); // expected output: 5

console.log(array1); // expected output: Array [4, 5, 1, 2, 3]

```

These are all the array of methods that will help you grow in your Software Developer Journey. While creating this blog I also learned a lot of things. If you liked it click on that liked button and comment you any feedbacks to help to improve the blog.