The Complete Reference for JavaScript Arrays
By: Javascript Jeep
Tags: Arrays In Javascript, Web Development, JavaScript, Arrays, Javascript Tips

Different ways of creating an array

var array = []; var array = Array(); var array = Array(3); // array of length 3 var array = new Array() var array = new Array(3) // array of length 3

1. Array.from()

The Array.from method creates a new shallow copy from an array-like or iterable object.

Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.

Syntax : Array.from(sourceArray [, mapFn [, thisArg] ])

Example 1: Array from a string

var str = "123"; //String is iterable Array.from(str); //['1','2','3']

Example 2: Duplicating an array

var array = [1,2,3,4,5]; var newArray = Array.from(array); //[1,2,3,4,5]

Example 3: Copying array with reference.

var array = [{name : 'john'}]; var newArray = Array.from(array); newArray[0].name; //john array[0].name = "Sam"; newArray[0].name ; //Sam The value is change to Sam in the copied array because it is shallow copied.

This also behave the same for, array inside an array:

var array = [[1,2]] var newArray = Array.from(array); array[0][0] = 5; newArray ; [[5,2]]

Example 4: Creating a new array of unique values from the array with duplicate values.

var array = [1,2,3,4,5,5,4,3,2,1]; var set = new Set(array); // removes duplicate elements var uniqueArray = Array.from(set) // [1,2,3,4,5]

Example 5: Using the map function.

var array = [1,2,3,4,5] var doubledArray = Array.from(array, (value, index) => value+value); doubledArray; [2,4,6,8,10];

In example 5, we can also create an Array from the object if the object has the property of length . If an object has a property of length Array.from methods thinks it is an iterable object and creates an array of that length and sets the value as undefined.

var obj = {length : 3} var array = Array.from(obj); console.log(array); // [undefined, undefined, undefined]

We can use the map function with the above code to create a function that will generate an array with numbers.

function fillArray(length) {



var obj = {length}; return Array.from(obj, (val, index) => index); } fillArray(10); [0,1,2,3,4,5,6,7,8,9]

You can pass the this argument as the third parameter and use it inside the map function.

If we pass undefined or null then it throws a cannot convert undefined or null to object error.

If a non-iterable object is passed, then it returns an empty-array .

2. Array.isArray()

This method checks whether the passed argument is an array.

Syntax: Array.isArray(value)

Returns true if it is an array, otherwise returns false .

Example value which returns true :

Array.isArray([]); //true Array.isArray([1]); //true Array.isArray(new Array());//true // Array.prototype is an array of functions Array.isArray(Array.prototype);

Values which return false :

// the result of all statement below evaluates to false Array.isArray(); Array.isArray({}); Array.isArray(null); Array.isArray(undefined); Array.isArray(100); Array.isArray('Array'); Array.isArray(true); Array.isArray(false); Array.isArray(new Uint8Array(32)); Array.isArray({ __proto__: Array.prototype });

3.Array.of()

The Array.of method creates a new array from the arguments passed.

Array.of(1) . // [1] Array.of(1,"str",[1,2],{n:10}) // [1, "string", Array(3), {…}]

4.Array.concat

This method merges the array or value passed and creates a new array. The array returned is the shallow copy of the arguments passed.

array1.concat[array2, arr3, arr4, .... arrN]

Example 1: Concat two arrays

var array = [1,2,3] var newArr = array.concat([7,8,9],[4,5,6]); //[1,2,3,7,8,9,4,5,6]

Example 2: We can also pass the primitive values or object as arguments

var array = [1] var newArr = array.concat("str",100,{obj:100})//[1,"str", {...}].

Example 3: Concatenation of array of arrays

var arr = [1,2]; var arr2 = [[1,2], [3,4]] var newArr = arr.concat(arr2) // [1,2,[1,2],[3,4]] The new Array is the shallow copy of the arguments so if we change the source it affects the copied object. arr2[0][1] = 9; //[1,2,[1,9],[3,4]]

5. Array.keys

The keys() method returns a new Array Iterator object that contains the indexes of the array.

var arr= [1,2,3]; var keys= arr.keys(); // it returns an Array iterator



console.log(...keys)

The difference between Object.keys() and Array.keys() is that Array.keys() also take holes as an index;

var arr = [1,,3]; Object.keys(arr); // [0,2] console.log(...arr.keys()) // 0,1,2

// undefined is not a hole var arr = [1, undefined, 2] Object.keys(arr); // [0,1,2] console.log(...arr.keys()) // 0,1,2

6. Array.values()

Array.values() method returns an Array iterator object that contains the values of the array. By using the iterator we can iterate through all the values of the array.

var array = ['🚒', '🚐', '🚚', '🚲']; var arrayIterator = array.values(); // Array iterator console.log(...arrayIterator) // 🚒,🚐,🚚,🚲 // or we can iterate through iterator using for ... of for (let vehicle of arrayIterator) { console.log(vehicle); } output : 🚒,🚐,🚚,🚲

7. Array.entries()

The entries method returns return an Array Iterator which contains the index-value pair of the array.

The key is the index of the array and the value is the value at that index.

var array = ['a', 'b', 'c']; var iterator = array.entries(); console.log(...iterator) // [0, "a"] [1, "b"] [2, "c"] or we can use for..of for (let entry of iterator) {

console.log(entry);

} // output

[0, "a"]

[1, "b"]

[2, "c"] or We can use destructing for (const [index, element] of iterator )

console.log(index, element); // output 0 "a"

1 "b"

2 "c"

8. Array.push()

The push method adds elements to the end of the array. It mutates the original array.

The push method returns the new length of the array after the item is pushed.

Syntax: array.push(n1, n2,...n)

var array = ['😀', '😃', '😎', '🤪', '🤩'] var newLen = array.push('😳'); //6 // [😀,😃,😎,🤪,🤩, 😳] newLen = array.push("hi","javascript jeep 🚙", 100); //9 // [😀, 😃, 😎, 🤪, 🤩, 😳,"hi", "javascript jeep 🚙", 100].

9. Array.unshift()

The unshift() method is the same as the push method, but the only difference is that it adds elements to the beginning of the array. It mutates the original array.

The unshift method returns the new length of the array after the item is added.

var array = ['😀', '😃', '😎', '🤪', '🤩'] var newLen = array.unshift('😳'); //6 // [😳, 😀,😃,😎,🤪,🤩] newLen = array.unshift("hi","javascript jeep 🚙", 100); //9 // ["hi", "javascript jeep 🚙", 😳, 😀,😃,😎,🤪,🤩]

10. Array.pop()

The pop() method removes the last element from the array. It mutates the original array.

The pop method returns the removed/popped element.

var array = ['🚒', '🚐', '🚚', '🚲']; array.pop(); // 🚲

11. Array.shift()

The unshift() method removes the first element from an array. It mutates the original array.

unshift returns the removed element.

var array = ['🚒', '🚐', '🚚', '🚲']; array.shift(); // 🚒

12. Array.toString()

The toString() methods convert the array to string and returns the string.

var array = [1, 2, '3', 'hi']; array.toString(); //1,2,3,hi"

If there is any object in it then it is converted as [object Object]

var array = [1, "string", {}, {name: "Javascript Jeep🚙"}] array.toString() // "1,string,[object Object],[object Object]"

If there is an array inside array then the array is flattened.

var array = [1, "string", [1,2,3]] array.toString(); // 1,string,1,2,3 var array = [1, "string", [1,2,3,[1,2]]] array.toString() // 1,string,1,2,3,1,2

13. Array.join()

This method creates a string by concatenating all the elements of the array.

Syntax: join(separator) here the separator is an optional string argument.

The strings are joined and each element is separated by the separator provided. If the separator is not passed then by default it is joined with , .

This method returns the joined string.

var array = ["Javascript", " Jeep", " 🚙"]; array.join(); // "Javascript, Jeep, 🚙" array.join("***"); // "Javascript*** Jeep*** 🚙"

If an array has one element, then the element is returned as a string without the separator.

var array = [" 🚙"]; array.join("-"); // "🚙"

If the array length is empty then it returns an empty string.

[].join(); //""

14 . Array.indexOf()

This method takes an input value and returns the first index of the value in the array.

If the element is not found then it returns -1 .

We can also specify the index from which we need to start searching.

This method search the element by using strict equality (===) checking.

Syntax : indexOf(elementToSearch, fromIndex)

fromIndex specifies from which index to start search.

var array = ['🚒', '🚐', '🚚', '🚲'];

The index can be denoted as

The array index is 🚒 → 0 , 🚐 → 1, 🚚 → 2, 🚲 → 3

We can also give fromIndex elements based on negative values

The array negative index is 🚒 → -4, 🚐 → -3, 🚚 → -2, 🚲 → -1

If the fromIndex is positive and greater than the array length then it returns -1 without searching.

If the fromIndex is negative and we need to calculate the computed index that can be calculated by (arrayLength + negativeIndex)

If the computed index is less or equal than -1 * array.length , the entire array will be searched.

Consider an array with length 4

Case 1: If the user provides fromIndex as -2, then the search starts from 4-2=2.

Case 2: If the user provides fromIndex as -10, then the search starts 4–10=-6 . In this case the entire array is searched.

Example:

var array = ['🚒', '🚐', '🚚', '🚲']; array.indexOf('🚲'); // 3 ------------------------------------------------------------------- // search an element from index 3 array.indexOf('🚲', 3); //3; because the 🚲 present in index 3 ------------------------------------------------------------------- //search an element from negative index -1 towards right. array.indexOf('🚲', -1);//3 because -1 th index is where 🚲present ------------------------------------------------------------------- array.indexOf('🚲', -2); // 3 ------------------------------------------------------------------- array.indexOf('🚒', -1) ; // this method search for 🚒 form index -1(1 in positive index) towards right , but the 🚒 present in 0 index so it returns -1 ------------------------------------------------------------------ array.indexOf('🚒', 10) ; fromIndex is positive and greater than the array length then it returns -1 without searching. ------------------------------------------------------------------

The indexOf method tests only for values and it doesn’t work for reference.

var a = [[1,2,3],3,4,5]; a.indexOf([1,2,3]); // -1 var a= [{},1,2,3]; a.indexOf({}); // -1

15. Array.lastIndexOf()

This method is similar to the indexOf method, but instead of returning the first index of the element passed, this method returns last index of the element in the array.

This method takes an input value and returns the last index of the passed value in the array.

If the element is not found then it returns -1 .

We can also specify the index from which we need to start searching.

This method search the element by using strict equality (===) checking.

Syntax: lastIndexOf(elementToSearch, fromIndex) .

Here the fromIndex specifies the index from which the search takes place in backward. When the index is negative, the array is still searched from back to front.

If we pass -1 then it starts the search from the last element of the array towards the first element.

var array= [1, 2, 3, 4]; array.lastIndexOf(2); // 1 array.lastIndexOf(7); // -1 array.lastIndexOf(4, 3); // 3 array.lastIndexOf(2, 2); // 1 array.lastIndexOf(2, -2); // 1 array.lastIndexOf(2, -1); // 1 array.lastIndexOf(2,-5); //-1

16. Array.findIndex()

This method returns the first element that satisfies the passed testing function.

If no element satisfies the condition then it returns -1 .

Syntax :

array.findIndex(

testingfunction,

thisArg(optional)

); // syntax of texting function testingfunc(

value,

index(optional),

array(optional)

)

Example: Find if an array contains even an number.

var array = [1,3,5,7,10]; function containsEven(value) { return value % 2 === 0; } array.findIndex(containsEven); // 4 // we can simplify the above function as array.findIndex(val => val%2===0 )

17. Array.includes()

This method test whether an element is present in the array. If it is in the array then it returns true else returns false .

This method follows same concept of Array.indexOf method.

Syntax: includes(elementToSearch, fromIndex)

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

18. Array.reverse()

This method reverse the array. This function mutates/reverses the original array.

This method returns the reversed array.

const array = [1, 2, 3];



console.log(array); // [1, 2, 3]



array.reverse();



console.log(array); // [3, 2, 1]

19. Array.flat()

This method flattens a multidimensional array and returns the flattened array.

We can specify the depth value which denotes how deep the flatten should happen. The default depth value is one. ☝

This method returns a new array with the sub-array elements concatenated into it.

Example 1:

var array = [1,2,3,4,[1,2]] var newArray = array.flat(); //[1,2,3,4,1,2]

Example 2 :

var array = [1, 2, 3, 4, [1, 2, [5, 6]] ]

// here the depth is 1 , so the [5,6] is not flattened var newArray = array.flat(); //[1,2,3,4,1,2, [5,6] ] // when we set depth to 2 , it also flatten the [5,6] element newArray = array.flat(2); // [1,2,3,4,1,2,5,6]

Example 3:

When we flat an array with holes, the holes are removed.

var arr = [1,,2,3] var newArray = arr.flat(); //[1,2,3]

20.Array.flatMap()

This method is similar to flat() , but the difference is that before flattening the array, each element of the array is mapped with the mapping function then it is flattened.

Another difference is that flatMap compared to flat only flattens to a depth of 1. We can’t specify how deep the flatten should happen.

Syntax:

var new_array = arr.flatMap(

mapFunc,

this(optional)

); // Syntax for the map function

mapFunction(

val,

index (optional),

array (optional)

)

Example: Convert all the numbers on the array into even then flatten the array

var array = [1,2,3,4,5,10]; function mapFunc(val) { // logic: if val = 3 => 3%2=1 then 3+1-> returns 4 return (val % 2) ? val +1 : val; } var newArray = array.flatMap(mapFunc);

In flatMap only the first level is flattened.

21. Array.some()

The array.some method checks whether any one of the elements in an array return true for the test function provided.

some returns true if any element passes the test, otherwise it returns false .

array.some(testFunction , thisArg(optional));

Example :

function isOdd(value, index, array) {

return value %2;

}



[2, 6, 8, 0, 4].some(isOdd); // false [12, 5, 8, 1, 4].some(isOdd); // true

If the array.some method is executed against an empty array, it returns false .

[].some(isOdd); //false

If we didn’t pass the testingFunction , then it will throw an error.

22. Array.every()

The array.every method checks whether all elements of the array returns true for the test function provided.

It returns true if all elements pass the test, otherwise it returns false if any one of the elements fails.

array.every(testFunction , thisArg(optional));

Example :

function isOdd(value, index, array) { return value %2; } [1, 7, 8, 1, 5].every(isOdd); // false [11, 5, 9, 1, 7].every(isOdd); // true

If the array.every method is executed against empty array , it returns false

[].every(isOdd); //true

If we didn’t pass the testingFunction, then it will throws an error.

23. Array.sort()

The sort method sorts the elements of the array and returns the sorted array.

We can pass compareFunction to implement custom sorting of the array.

Syntax : sort(compareFunction)

Here the compareFunction passed as an argument is optional.

Example: Without passing a compareFunction . The default sorting of the array is based on the string representation. Read the description in the example if this doesn’t make sense.

Example of default sorting. var arr = [1, 2, 3, 200, 100]; arr.sort() arr ; // [1, 100, 2, 200, 3] The reason for the above result is, by default, sorting is based on strings. It first it converts the value to the string, then values are compared by their sequences of UTF-16 code units values.

Example: Passing a compareFunction

The compare function should return (0, >0, <0).

If the compare function returns:

0 or less than 0 → leave a and b unchanged

and unchanged greater than 0 → swap position

function ascendingOrder(num1, num2) {

if(num1 === num2) return 0;

if(num1 < num2) return -1;

if(num1 > num2) return 1;

} var arr = [1, 2, 3, 200, 100]; arr.sort(ascendingOrder)

// the above function can be simplified by /* logic :

if a > b → (a-b) returns >0, then there is a swap if a === b → (a-b) returns 0 , so no swap if a < b; (a- b) returns <0 , no swap */ arr.sort((a, b) => a-b ); To sort an array in descending order do it in reverse arr.sort( (b, a) => a - b )

24. Array.fill()

This method replaces (mutates) the values of the array with the given value for the given range.

Syntax : array.fill(value, startIndex(optional), endIndex(optional))

It returns the modified array and also changes the source array.

If the startIndex (default value: 0 ) and endIndex (default value: array.length ) is not passed, the entire array is replaced.

var array = [1,2,3,4,5] array.fill(3, 2, 4) // [1, 2, 3, 3, 5] array.fill(8,1,2) // [1, 8, 3, 3, 5] if the start and end index is same then there is no fill takes place array.fill(9,1,1) // [1, 8, 3, 3, 5] we can also pass negative index for start and end index argument array.fill(9,-3,-2) // [1, 8, 9, 3, 5]

if we pass start index < end index then no fill array.fill(19,4,3) // [1, 8, 9, 3, 5]

Creating an Array of elements with default values:

var array = new Array(5).fill(0); // [0,0,0,0,0]

If we try to fill the element with objects object, then the references are copied.

var array = [1,2,3]; var obj = {name : "Javascript heap"}; array.fill(obj); obj.name = "Javascript Jeep 🥶"; array //

[ {name: “Javascript Jeep 🥶”}

{name: “Javascript Jeep 🥶”}

{name: “Javascript Jeep 🥶”} ] array[0].name = "JAVASCRIPT JEEP 🥶"; array //

[ {name: “JAVASCRIPT JEEP 🥶”}

{name: “JAVASCRIPT JEEP 🥶”}

{name: “JAVASCRIPT JEEP 🥶”} ];

25. Array.reduce()

The reduce function executes a reducer function on each element of the array, resulting in a single value output.

This method returns the value that is returned from the reducer function (accumulator value).

syntax: Array.reduce(reducerFunction, initialAccumulatorValue(opt)); reducerFunction syntax: reducerFunction(accumulator, value, index(opt), srcArray(opt)) ;

The accumulator is the final output returned by the reducer function.

Example sum of array elements:

var array = [1,2,3,4,5] function reducerFunction(accumulator, value) { return accumulator + value; } var sum = array.reduce(reducerFunction) ; //15 // the above function can be simplified as array.reduce( (acc, val) => acc+val )

If the initialAccumulatorValue is not provided, the reducer function execution starts from first index .

In the above example, every element of the array is passed to the reducer function. In that function, each value is added to the accumulator (final result).

Example with initialAccumulatorValue :

var array = [1,2,3,4,5] function reducerFunction(accumulator, value) { return accumulator + value; } var sum = array.reduce(reducerFunction, 100) sum ;// 115 // the above function can be simplified as array.reduce( (acc, val) => acc+val ), 100)

If the initial value is provided then the reducer function execution starts from the 0th index.

26. Array.reduceRight()

This method is same as the reduce method, except the reducer function is executed against the element of array from right to left.

Example:

var array = [ " hi ", " from", " Javascript Jeep 🚙 "] array.reduce( (acc, val) => acc + val );

output : hi from Javascript Jeep 🚙 array.reduceRight( (acc, val) => acc * val );

output : Javascript Jeep 🚙 from hi.

27 . Array.filter()

This method filter the array elements based on the function provided.

The filter method executes the testingFunction against all elements of the array and returns a new array with elements which return true on the testing function. If the testing function returns false for an element, it does not appear in the new array. This method doesn’t alter/mutate the source array.

Syntax:

syntax : filter

---------------- Array.filter(testingFunction, thisArg(optional)) syntax :testingFunction

---------------------- testingFunction(value, index(optional), array(optional))

Example:

function filterEvenNumbers(value) { return value % 2 === 0; } var array = [2, 15, 8, 10, 44]; var evenNumbers = array.filter(filterEvenNumbers); evenNumbers // [2,8,10,44]

// it can be simplified as even = array.filter( (val) => val %2 ===0 )

28. Array.map()

The map function executes a function provided against all the elements of the array and produce a new array and returns that array.

Syntax:

syntax : map

-------------- var new_array = array.map(mappingFunction ,thisArg(optional))

// syntax : mappingFunction

---------------------------- mappingFunction(val, index(optional), srcArray(optional)) ;

Example:

function square(val) {



return val * val; } var array = [1,2,3,4,5]; var squaredNumbers = array.map(square); //1,4,9,16,25 //using arrow function array.map(v => v * v);

Example 2: Mapping an array of objects and getting the value of the object as an array.

var array = [{name : "brandi love"}, {name : "julia ann"} ]; var upperCaseNames = array.map( (obj) => obj.name.toUpperCase() ); //["BRANDI LOVE", "JULIA ANN"]

29. Array.forEach()

The forEach method executes a method that is provided as an argument against every element of the array once.

Syntax: forEach(callback, thisArg(optional))

It is a replacement for the traditional for loop.

const numbers = [1,2,3,4,5]; const copy = [];

// old way

---------- for (let i=0; i<numbers.length; i++) { copy.push(items[i]); }



// cool way

------------ items.forEach(function(item){ copy.push(item); });

Example 2:

var names = ["ironman", "superman", "batman"] names.forEach( (ele) => { console.log( ele.toUpperCase() ) }); // IRONMAN

//SUPERMAN

//BATMAN

30. Array.slice()

The slice method returns a new array with a portion of the source array — it returns sub-arrays.

Syntax : arr.slice(beginIndex(optional), endIndex(optional))

The default value of beginIndex is 0 .

If the beginIndex is greater than array length, then an empty array [] is returned.

We can also use a negative index for beginIndex and endIndex .

If the endIndex is not passed or endIndex is greater than array length, then slice all elements from the beginIndex to the end of the array.

It returns a shallow copy of the array, the original array is not modified.

var numbers = [1,2,3,4,5,6]; var greaterThan3= numbers.slice(3); [4,5,6] greaterThan3= numbers.slice(3,5); [4,5] greaterThan3= numbers.slice(3,6); [4, 5, 6]

If the endIndex is smaller than startIndex then an empty array is returned.

If the source array contains an object, then the reference is copied.

var array = [ {name: "john"}, {name : "stephen"} ]; var newArray = array.slice();

//if we don't provide start&end index then whole array is copied array[0].name = "JOHN"; // newArray has an reference of array[0] so the value at newArray is also changed newArray[0].name ; //JOHN

31 . Array.splice()

The splice() method alters or removes or replaces or add elements to the source array. It is a mutating action on the original array.

Syntax:

var DeletedItemsArray = array.splice(start, deleteCount, item1, item2,...itemN); startIndex index from which the delete or add should take place. deleteCount number of elements to be deleted If deleteCount is omitted, or if its value is equal-to or larger than array.length - start, then all the elements from start to the end of the array will be deleted.

item1,...--> . elements to be added from the startIndex provided

here deleteCount, items value are optional.

This method returns the array containing deleted items.

Example:

var array = [1,2,3,4,5] var deletedItems = array.splice(0,0) //doesn't delete any element because delCount-->0 ------------------------------------------------------------------- var array = [1,2,3,4,5] var deletedItems = array.splice(0,1); //[1] deletes 1 element from 0th index ------------------------------------------------------------------- var array = [1,2,3,4,5] var deletedItems = array.splice(0, 1, 2, 4); //[1] deletes 1 element from 0th index and insert 2, 4 array; //[2, 4, 2, 3, 4, 5] -------------------------------------------------------------------

var array = [1,2,3,4,5] var deletedItems = array.splice(2); //[3,4,5] deletes from index:3 to last element

because default delCount : arrayLength array; //[1,2] -------------------------------------------------------------------

var array = [1,2,3,4,5] var deletedItems = array.splice(-3, 1, 2, 4); //[3] deletes 1 element from -3rd index and insert 2, 4 array; // [1, 2, 2, 4, 4, 5]

------------------------------------------------------------------- var deletedItemsArray = array.splice(); //[] deletedItemsArray = array.splice(undefined); // [1,2,3,4,5]

Follow Javascript Jeep🚙 🥶.