ARRAYS In JavaScript (JS) : A Quick check guide...
It's time to flex those array muscles... πͺπͺπͺ
Table of contents
- π€π€π€ What is Array ? π€π€π€
- π€·π€·π€· Array Declaration π€·π€·π€·
- π₯π₯π₯ Shallow copy π₯π₯π₯
- π¨ββοΈπ¨ββοΈπ¨ββοΈ Static methods π¨ββοΈπ¨ββοΈπ¨ββοΈ
- π·ββοΈπ·ββοΈπ·ββοΈ Instance properties π·ββοΈπ·ββοΈπ·ββοΈ
- π©π»βπΌπ©π»βπΌπ©π»βπΌ Instance methods π©π»βπΌπ©π»βπΌπ©π»βπΌ
- Array.prototype.at()
- Array.prototype.concat()
- Array.prototype.copyWithin()
- Array.prototype.entries()
- Array.prototype.every()
- Array.prototype.fill()
- Array.prototype.filter()
- Array.prototype.find()
- Array.prototype.findIndex()
- Array.prototype.findLast()
- Array.prototype.findLastIndex()
- Array.prototype.flat()
- Array.prototype.flatMap()
- Array.prototype.forEach()
- Array.from()
- Array.prototype.includes()
- Array.prototype.indexOf()
- Array.isArray()
- Array.prototype.join()
- Array.prototype.keys()
- Array.prototype.lastIndexOf()
- Array.prototype.map()
- Array.of()
- Array.prototype.pop()
- Array.prototype.push()
- Array.prototype.reduce()
- Array.prototype.reduceRight()
- Array.prototype.reverse()
- Array.prototype.shift()
- Array.prototype.slice()
- Array.prototype.some()
- Array.prototype.sort()
- Array.prototype.splice()
- Array.prototype.toString()
- Array.prototype.unshift()
- Array.prototype.values()
π©βπ«π©βπ«π©βπ« It is time to dive into the world of arrays and what great way to start other than getting a quick refresher on it's basic methodology and the various methods it associates with. π©βπ«π©βπ«π©βπ«
Please note that the basic concept of arrays remains the same across languages like C, C++, Java, JavaScript so if you are familiar with these languages, learning arrays in javascript (JS) would be a breeze for you.
But ofcourse, you would find some differences which makes arrays in javascript standout π©βπ³π©βπ³π©βπ³
π€π€π€ What is Array ? π€π€π€
- In JS, arrays are basically objects. The typeof operator in JavaScript returns "object" for arrays.
- They are are resizable and can contain a mix of different data types. This is unlike languages like C, C++, Java wherein arrays are collection of just similar datatypes.
- The first element of an array is at index 0, the second is at index 1, and so on...
π€·π€·π€· Array Declaration π€·π€·π€·
- A simple array declaration looks as follows :
let arr1 = ['Apple', 'Orange', true, 5, -2.5];
console.log(arr1);
Output :
π₯π₯π₯ Shallow copy π₯π₯π₯
- This is a very important concept that needs to be understood while copying arrays.
- JS works on the concept of shallow copies.
- A shallow copy of an object is a copy whose properties share the same references (point to the same underlying values) as those of the source object from which the copy was made. As a result, when you change either the source or the copy, you may also cause the other object to change too β and so, you may end up unintentionally causing changes to the source or copy that you don't expect. That behavior contrasts with the behavior of a deep copy, in which the source and copy are completely independent.
- Deep copy of an object is a completely new object which has different references. Here we use new keyword to create a completely brand new array object but this is beyond the scope of this article, keep tuned for future articles on this topic.
let arr1 = ['Apple', 'Orange', true, 5, -2.5];
console.log(arr1);
let arr2 = arr1;
arr2[1] = 'Guava';
console.log(arr1);
π¨ββοΈπ¨ββοΈπ¨ββοΈ Static methods π¨ββοΈπ¨ββοΈπ¨ββοΈ
Array.from()
- The Array.from() static method creates a new, shallow-copied Array instance from an iterable or array-like object.
console.log(Array.from('Manikisranked1among100'));
Array.isArray()
- The Array.isArray() method determines whether the passed value is an Array.
console.log(Array.isArray('Manik100'));
console.log(Array.isArray(['25','ram',true]));
Array.of()
- The Array.of() method creates a new Array instance from a variable number of arguments, regardless of number or type of the arguments.
console.log(Array.of('manik', 8, true, -8.5, 'apple'));
π·ββοΈπ·ββοΈπ·ββοΈ Instance properties π·ββοΈπ·ββοΈπ·ββοΈ
Array.prototype.length
- The length property of an object which is an instance of type Array sets or returns the number of elements in that array.
let arr1 = ['tom', 'jerry', 875, true, undefined];
console.log(arr1.length);
π©π»βπΌπ©π»βπΌπ©π»βπΌ Instance methods π©π»βπΌπ©π»βπΌπ©π»βπΌ
Array.prototype.at()
- The at() method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.
let arr1 = ['tom', 'jerry', 875, true, undefined];
console.log(arr1.at(1));
console.log(arr1.at(-2));
Array.prototype.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.
let arr1 = ['tom', 'jerry', 875, true, undefined];
let arr2 = [11, 5, 0, -8, false, null];
let arr3 = arr1.concat(arr2);
console.log(arr3);
Array.prototype.copyWithin()
- The copyWithin() method shallow copies part of an array to another location in the same array and returns it without modifying its length.
let arr1 = ['tom', 'jerry', 875, true, undefined, 'tata', 'bye', 99];
// copyWithin(target)
// copyWithin(target, start)
// copyWithin(target, start, end)
console.log(arr1);
console.log(arr1.copyWithin(2));
console.log(arr1.copyWithin(0,3));
console.log(arr1.copyWithin(0,3,4));
console.log(arr1.copyWithin(0,3,5));
console.log(arr1);
Array.prototype.entries()
- The entries() method returns a new Array Iterator object that contains the key/value pairs for each index in the array.
let arr1 = ['tom', 'jerry', 875, true, undefined, 'tata', 'bye', 99];
let iterator = arr1.entries();
console.log(iterator);
console.log(iterator.next().value);
console.log(iterator.next().value);
console.log(iterator.next().value);
console.log(iterator.next().value);
console.log(iterator.next().value);
console.log(iterator.next().value);
console.log(iterator.next().value);
console.log(iterator.next().value);
console.log(iterator.next().value);
Array.prototype.every()
- The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
let arr2 = [1, 7, 39, -9, 0, 55]
console.log(arr2.every(function isBelow(e){
return e<100;
}));
![array12.JPG](https://cdn.hashnode.com/res/hashnode/image/upload/v1661657780846/oUlbwePVQ.JPG align="left")
arr2 = [1, 7, 39, -9, 0, 550]
console.log(arr2.every(function isBelow(e){
return e<100;
}));
Array.prototype.fill()
- The fill() method changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length). It returns the modified array.
let arr1 = ['tom', 'jerry', 875, true, undefined, 'tata', 'bye', 99];
// fill(value)
// fill(value, start)
// fill(value, start, end)
console.log(arr1.fill(100,2,4));
console.log(arr1.fill('abc',2,4));
console.log(arr1.fill(0,2));
console.log(arr1.fill(-99));
Array.prototype.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.
let arr2 = ['tom', 'jerry', 'tata', 'bye'];
let myfilter = arr2.filter(e => e.length>4);
console.log(myfilter);
Array.prototype.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.
let arr3 = [23, 5, 10, 100, -4, 52]
let myfind = arr3.find(e => e<20);
console.log(myfind);
Array.prototype.findIndex()
- The findIndex() method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.
let arr3 = [23, 5, 10, 100, -4, 52]
let myfindindex = arr3.findIndex(e => e<20);
console.log(myfindindex);
Array.prototype.findLast()
- The findLast() method returns the value of the last element in an array that satisfies the provided testing function. If no elements satisfy the testing function, undefined is returned.
let arr3 = [23, 5, 10, 100, -4, 52];
let myfindlast = arr3.findLast(e => e<25);
console.log(myfindlast);
Array.prototype.findLastIndex()
- The findLastIndex() method returns the index of the last element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.
let arr3 = [23, 5, 10, 100, -4, 52];
let myfindlastIndex = arr3.findLastIndex(e => e<25);
console.log(myfindlastIndex);
Array.prototype.flat()
- The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat());
const arr2 = [0, 1, 2, [[[3, 4]]]];
console.log(arr2.flat(2));
Array.prototype.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);
Array.prototype.forEach()
- The forEach() method executes a provided function once for each array element.
let arr1 = ['tom', 'jerry', 875, true, undefined, 'tata', 'bye', 99];
arr1.forEach(e => console.log(e));
Array.from()
- The Array.from() static method creates a new, shallow-copied Array instance from an iterable or array-like object.
console.log(Array.from('manik1000'));
console.log(Array.from([1,2,3,4,5], e => e+1));
Array.prototype.includes()
- The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
let arr1 = ['tom', 'jerry', 875, true, undefined, 'tata', 'bye', 99];
console.log(arr1.includes(true));
console.log(arr1.includes('tata'));
console.log(arr1.includes(99));
console.log(arr1.includes(-99));
Array.prototype.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.
let arr2 = ['tom', 'jerry', 'tata', 'bye', 'tata', 'tom', 'snoopy'];
console.log(arr2.indexOf('tata'));
console.log(arr2.indexOf('tata', 3));
console.log(arr2.indexOf('tom', 1));
console.log(arr2.indexOf('tommy'));
Array.isArray()
- The Array.isArray() method determines whether the passed value is an Array.
console.log(Array.isArray('manik'));
console.log(Array.isArray([1,55,1,20]));
console.log(Array.isArray({prod: 'mac', price: 50000, version: 'latest'}));
Array.prototype.join()
- 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.
let arr2 = ['tom', 'jerry', 'tata', 'bye', 'tata', 'tom', 'snoopy'];
console.log(arr2.join());
console.log(arr2.join(' '));
console.log(arr2.join('*'));
Array.prototype.keys()
- The keys() method returns a new Array Iterator object that contains the keys for each index in the array.
let arr2 = ['tom', 'jerry', 'tata', 'bye', 'tata', 'tom', 'snoopy'];
let iterator = arr2.keys();
console.log(iterator);
for (const i of iterator) {
console.log(i);
}
Array.prototype.lastIndexOf()
- The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex.
let arr2 = ['tom', 'jerry', 'tata', 'bye', 'tata', 'tom', 'snoopy', 'tom'];
console.log(arr2.lastIndexOf('tom'));
console.log(arr2.lastIndexOf('tata'));
console.log(arr2.lastIndexOf('jerry'));
console.log(arr2.lastIndexOf('tommy'));
Array.prototype.map()
- The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
let arr3 = [23, 5, 10, 100, -4, 52];
console.log(arr3.map(e => e*2));
Array.of()
- The Array.of() method creates a new Array instance from a variable number of arguments, regardless of number or type of the arguments.
- The difference between Array.of() and the Array constructor is in the handling of integer arguments: Array.of(7) creates an array with a single element, 7, whereas Array(7) creates an empty array with a length property of 7. (That implies an array of 7 empty slots, not slots with actual undefined values.)
console.log(Array.of(10));
console.log(Array.of(2,7,-4,'ram',true));
Array.prototype.pop()
- The pop() method removes the last element from an array and returns that element. This method changes the length of the array.
let arr1 = ['tom', 'jerry', 875, true, undefined, 'tata', 'bye', 99];
console.log(arr1.pop());
console.log(arr1);
console.log(arr1.pop());
console.log(arr1);
Array.prototype.push()
- The push() method adds one or more elements to the end of an array and returns the new length of the array.
let animals = [];
console.log(animals.push('cat'));
console.log(animals);
console.log(animals.push('dog'));
console.log(animals);
console.log(animals.push('mouse'));
console.log(animals);
Array.prototype.reduce()
- The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
- The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0).
let arr4 = [1, 2, 3, 4, 5, 6];
console.log(arr4.reduce((prev, curr) => (prev + curr)));
Array.prototype.reduceRight()
- The reduceRight() method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value.
const array1 = [[0, 1], [2, 3], [4, 5]];
const result = array1.reduceRight((accumulator, currentValue) => accumulator.concat(currentValue));
console.log(result);
Array.prototype.reverse()
- The reverse() method 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 stated.
let arr3 = [23, 5, 10, 100, -4, 52];
console.log(`Original array : ${arr3}`);
console.log(`Reversed array : ${arr3.reverse()}`);
console.log(`Changed array : ${arr3}`);
Array.prototype.shift()
- The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.
let arr3 = [23, 5, 10, 100, -4, 52];
console.log(`Removed element is ${arr3.shift()}`);
console.log(`New array is ${arr3}`);
Array.prototype.slice()
- The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.
let arr2 = ['tom', 'jerry', 'tata', 'bye', 'tata', 'tom', 'snoopy', 'tom'];
console.log(arr2.slice(2));
console.log(arr2.slice(2,4));
console.log(arr2.slice(-2));
console.log(arr2.slice(2,-1));
Array.prototype.some()
- The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.
let arr3 = [23, 5, 10, 100, -4, 52];
console.log(`Atleast one element is even ? : ${arr3.some(e => e%2===0)}`);
let arr4 = [23, 5, 11, 101, -5, 53];
console.log(`Atleast one element is even ? : ${arr4.some(e => e%2===0)}`);
Array.prototype.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, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
The time and space complexity of the sort cannot be guaranteed as it depends on the implementation.
let arr3 = [23, 5, 10, 100, -4, 52];
console.log(arr3.sort());
console.log(arr3.sort((a,b) => {
if(a<=b){
return -1;
}
else{
return 1;
}
}));
const months = ['March', 'Jan', 'Feb', 'Dec'];
console.log(months.sort());
Array.prototype.splice()
- The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. To access part of an array without modifying it, see slice().
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
console.log(months);
months.splice(4, 1, 'May');
console.log(months);
months.splice(3, 2, 'Double');
console.log(months);
Array.prototype.toString()
- The toString() method returns a string representing the specified array and its elements.
let arr1 = ['tom', 'jerry', 875, true, undefined, 'tata', 'bye', 99];
console.log(arr1.toString());
Array.prototype.unshift()
- The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
let arr3 = [23, 5, 10, 100, -4, 52];
console.log(arr3.unshift(200,300));
console.log(arr3);
Array.prototype.values()
- The values() method returns a new array iterator object that contains the values for each index in the array.
let arr3 = [23, 5, 10, 100, -4, 52];
let iterator = arr3.values();
console.log(iterator);
for (const key of iterator) {
console.log(key);
}
πππ In the end I would like to mention that I learnt so much writing this article that it shows the mammoth of information that can be manipulated by these array methods. πππ
Ofcourse, I do not expect you to memorize them all, like I always say keep practising hard and you would find these methods quite useful π€π»π€π»π€π»