Important methods of Javascript Array

The JavaScript Array class is a global object that is used in the construction of arrays; which are high-level, list-like objects.

Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed.

Arrays cannot use strings as element indexes (as in an associative array) but must use integers.

Array Index

Create an Array:

let names = ['Amma', 'Appa', 'Ajja', 'Akka'];
console.log(names)
console.log(names.length)
// (4) ["Amma", "Appa", "Ajja", "Akka"]
// 4

#1: forEach(): Looping over an Array

forEach() calls a provided callback function once for each element in an array in ascending order.

names.forEach(function(element) {
    console.log(element)
})
// Amma
// Appa
// Ajja
// Akka

If we want to get the index of each element then forEach also provides a parameter in its callback function.

names.forEach(function(element, index) {
    console.log(index, element)
})
// 0 "Amma"
// 1 "Appa"
// 2 "Ajja"
// 3 "Akka"

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the foreEach() method is the wrong tool.

forEach() expects a synchronous function. forEach() does not wait for promises.

#2: push() – Add to the end of an Array

The push method appends values to an array. This method returns the new length of the array.

string is also array-like objects. But this push() cannot be apply on string

let names = ['Amma', 'Appa', 'Ajja', 'Akka'];
let newLength = names.push("Anuj")
console.log(newLength)
console.log(names)
// 5
// (5) ["Amma", "Appa", "Ajja", "Akka", "Anuj"]

#3: pop() – Remove from the end of an Array

The pop method removes the last element from an array and returns that element. This method changes the length of the array. It returns removed element

let names = ['Amma', 'Appa', 'Ajja', 'Akka'];
// Before removal
console.log(names)
let removedElem = names.pop()
console.log(removedElem)
// After removal
console.log(names)

// (5) ["Amma", "Appa", "Ajja", "Akka"]
// "Akka"
// (4) ["Amma", "Appa", "Ajja"]

#4: slice() – Extracts a section of the calling array

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included) where begin and end represent the index of items in that array. The original array will not be modified.

If begin is undefined, slice begins from index 0. If begin is greater than the index range of the sequence, an empty array is returned.

let names = ['Amma', 'Appa', 'Ajja', 'Akka', "Anuj"];
let newArray = names.slice(); // return complete array
let newArray2 = names.slice(2); // return array from index 2 till end
let newArray3 = names.slice(2, 4) //return array from index 2 till 3
console.log(newArray)
console.log(newArray2)
console.log(newArray3)

// (5) ["Amma", "Appa", "Ajja", "Akka", "Anuj"]
// (3) ["Ajja", "Akka", "Anuj"]
// (2) ["Ajja", "Akka"]

A negative index can be used, indicating an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence.

let names = ['Amma', 'Appa', 'Ajja', 'Akka', "Anuj"];
let arr1 = names.slice(-2)
// if we give out of range value then it will return full array
let arr2 = names.slice(-6)

console.log(arr1)
console.log(arr2)

// (2) ["Akka", "Anuj"]
// (5) ["Amma", "Appa", "Ajja", "Akka", "Anuj"]

arr.slice(?start, ?end)

syntax

#5: join() – Joins all elements of an array into a string

The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string.

If the array has only one item, then that item will be returned without using the separator.

join
let names = ['Amma', 'Appa', 'Ajja', 'Akka', "Anuj"];
console.log(names.join())
console.log(names.join(''))
console.log(names.join('-'))
console.log(names.join('_'))

// "Amma,Appa,Ajja,Akka,Anuj"
// "AmmaAppaAjjaAkkaAnuj"
// "Amma-Appa-Ajja-Akka-Anuj"
// "Amma_Appa_Ajja_Akka_Anuj"

arr.join(?separator)

syntax

#6: splice() – Adds and/or removes elements from an array

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

let names = ['Amma', 'Appa', 'Ajja', 'Akka', "Anuj"];

names.splice(1, 0, 'Ram');
// inserts at index 1
console.log(names);
// expected output: (6) ["Amma", "Ram", "Appa", "Ajja", "Akka", "Anuj"]

names.splice(4, 1, 'Krishna');
// replaces 1 element at index 4
console.log(names);
// expected output: (6) ["Amma", "Ram", "Appa", "Ajja", "Krishna", "Anuj"]

names.splice(1,1)
// remove 1 element at index 1
console.log(names)
// expected output: (5) ["Amma", "Appa", "Ajja", "Krishna", "Anuj"]

arr.splice(start, ?deleteCount, …items)

syntax

#7: filter() – filter array on the basis of condition

The filter() method creates a new array with all elements that pass the test implemented by the provided function. It doesn’t change the existing array.

let newArray = arr.filter(callback(element, ?index, array), ?thisArg)

syntax
const words = ['spray', 'limit', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

words.filter(function(word) {
    return word.includes('r');
})
// expected output: (4) ["spray", "exuberant", "destruction", "present"]
function isBigEnough(value) {
  return value >= 10
}

let filtered = [12, 5, 8, 130, 44].filter(isBigEnough)
// filtered is [12, 130, 44]
// Modifying each words
let words = ['spray', 'limit', 'exuberant', 'destruction','elite', 'present']

const modifiedWords = words.filter( (word, index, arr) => {
  arr[index+1] +=' extra'
  return word.length < 6
})

console.log(modifiedWords)
// Notice there are three words below length 6, but since they've been modified one is returned
// ["spray"]

#8: map() – Create a new array with the results of calling function

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

let new_array = arr.map(callback( currentValue, ?index, ?array), ?thisArg)

syntax
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]
//Using map to reformat objects in an array

let kvArray = [{key: 1, value: 10}, 
               {key: 2, value: 20}, 
               {key: 3, value: 30}]

let reformattedArray = kvArray.map(obj => {
   let rObj = {}
   rObj[obj.key] = obj.value
   return rObj
})
// reformattedArray is now [{1: 10}, {2: 20}, {3: 30}], 

// kvArray is still: 
// [{key: 1, value: 10}, 
//  {key: 2, value: 20}, 
//  {key: 3, value: 30}]

When not to use map()

Since map builds a new array, using it when you aren’t using the returned array is an anti-pattern; use forEach or for-of instead.

You shouldn’t be using map if:

  1. you’re not using the array it returns; and/or
  2. you’re not returning a value from the callback.

A Tricky case of map which might be confusing using parseInt() on map.

["1", "2", "3"].map(parseInt)

While one might expect [1, 2, 3], the actual result is [1, NaN, NaN].

parseInt is often used with one argument, but takes two. The first is an expression and the second is the radix to the callback function, Array.prototype.map passes 3 arguments:

  • the element
  • the index
  • the array

The third argument is ignored by parseInt—but not the second one! This is the source of possible confusion.

Here is a concise example of the iteration steps:

// parseInt(string, radix) -> map(parseInt(value, index))
/*  first iteration  (index is 0): */ parseInt("1", 0)  // 1
/*  second iteration (index is 1): */ parseInt("2", 1)  // NaN
/*  third iteration  (index is 2): */ parseInt("3", 2)  // NaN
['1', '2', '3'].map( str => parseInt(str) ) // [1, 2, 3]

// A simpler way to achieve the above, while avoiding the "gotcha":
['1', '2', '3'].map(Number)  // [1, 2, 3]

Some other useful methods are:

shift():

Removes the first element from an array and returns that removed element. This method changes the length of the array.

const array1 = [1, 2, 3];

const firstElement = array1.shift();

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

console.log(firstElement);
// expected output: 1

unshift():

Adds one or more elements to the front of an array, and returns the new length of the array.

let names = ['Amma', 'Appa', 'Ajja', 'Akka'];
let newLength = names .unshift('Berry') // add to the front
// ["Berry", "Amma", "Appa", "Ajja", "Akka"]

sort():

Sorts the elements of an array in place and returns the array.  The default sort order is ascending. We can pass our compare function in sort().

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

includes():

The include method determines whether the array contains valueToFind, returning true or false as appropriate.

onst array1 = [1, 2, 3];

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

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Leave a Reply