JavaScript: Working with Array

javascript

JavaScript Array is one of the most used items by a Programmer. You can read more more on Arrays on MDN.

Defining an array

var arr = [1, 2];
var arr1 = new Array(1,2);
var arr2 = new Array(length);
// This will create an array of the given length, but won't initialize the values. The values would be empty and not undefined.

Looping through Array

arr.forEach((item, index, array) => {
    // item => the current item
    // index => index of the current item
    // array => the actual array passed
});

Retrieving an item from array

arr[2]; // This will return 3rd element in the array
arr[2] = arr[02] = arr['2'] != arr['02']
arr.indexOf(2); // Returns the index of the item, or -1 if not found
arr[12] = 17;
Object.keys(arr); // Will return the keys/indexes of all the elements
// 0,1,2,12                        

Performing actions on the Array

arr.push(3); // Adds an item to the end of the array and returns the new length of the array
arr.pop(); // Removes the last item from the array and returns the removed item
arr.shift(); // Removes the first element from the array and returns the removed item
arr.unshift(4); // Adds an item to the start of the array and returns the new length of the array
arr.reverse(); // Reverses the original array and returns the reversed array.

These actions can be applied on Array like objects using the apply() or call() on the 

Array.prototype.funcName.call/apply(obj) or
[].push.call(this, elem)

Slice – Get part of an Array

arr.slice(startIndex?, endIndex?); // This will return a copy of the items from the
startIndex to the endIndex, excluding the endIndex.

This will not modify the original array.
If endIndex isn’t provided, then a copy from the startIndex to the last item is returned
If both startIndex and endIndex isn’t provided, then a copy of the whole array is returned.

let arrCopy = arr.slice(); // Shallow copy an array

Splice – Getting a piece of an array or replacing some part of the array

arr.splice(startIndex, numberOfItems?, ...itemsToReplaceWith?); // This will return the items that has been spliced.

The items spliced are removed from the original array.
If numberOfItems isn’t provided, then the array is spliced till the last.

Array.from() will take any object that can be converted to an array and returns the array.
Array.from(param1, param2);
param1 is the data that can be converted to an array. Can be a string which can be split to an array, or a Set, an Array, etc.
param2 is a callback function which will be run on every element of the array.

Array.isArray(arr) can be used to check if a variable is an array. Returns true/false

Sorting an Array

arr.sort() by default takes the elements of the Array, converts the values to Strings and then sorts them by comparing the UTF-16 values
The sort() takes a compareFunction to provide custom sorting
The compare() takes 2 parameters, basically 2 elements from the Array and compares them. If the compare() returns < 0, then a < b, so the position remains intact. If it returns = 0, then a = b, so the elements are kept as it is. If it returns > 0, then a > b, and then the 2 values exchange places.

For sorting number for example:

arr.sort((a,b) => a-b)

For objects with some value to to be sorted,

arr.sort((a,b) => a.price - b.price);

Array.of() will use the arguments to create an array of it. It is similar to Array constrctor, except if only one number attribute is passed to the constructor function, it will return an Array with that many number of items, but Array.of() will return an array with that number as the only element.

new Array(4) = [ , , , ]
Array.of(4) = [4]
arr.copyWithin(copyToIndex, copyStartIndex, copyEndIndex?:number)

If copyEndIndex isn’t provided, all the elements from the copyStartIndex to the last element of the array will be copied

arr.fill(fillValue, fillStartIndex?, fillEndIndex?)

Copy the given fill value in the indexes provided.
If NaN is provided as index, then the value isn’t filled.

Concatenate multiple arrays

arr1.concat(arr2, arr3, ..) - Concats everything and returns it. The original array remains unchanged
arr.includes('Apple') // Will return true or false based on the item is there or not. Similar to arr.indexOf() without the index
arr.join(str?) - Joins all the elements in the array with the str provided and returns it.

Example AppleBanana(”) or Apple,Banana(‘,’)

arr.lastIndexOf('Apple', fromIndex) - Returns the last found index of the given item. The search is done backwards

fromIndex informs from which index to start backwards

arr.toString() – Returns the csv presentation of the array values

Iteration methods

arr.entries() - Returns an Array iterator with key/value pairs for each item of the array
iterator = arr.entries();
iterator.next().value - [0, 'Apple']
for (const [index, item) of arr.entries()) {
    console.log(index, item);
}
arr.every(func, this?) - Returns true if all the elements in the array pass the func.
arr.some(func, this?) - Returns true if atleast one element passes the func
func(item, index?, array?)

arr.filter(callbackFunc, this) – This returns a new array with the items that pass the callbackFunc. The callbackFunc needs to return true/false. The original array remains unchanged.
callbackFunc(item, index?, array?)

ar.find(testFunc, this) – Returns the first element that satisfies the testFunc
testFunc(item, index?, array?)

If modifications are done while the iterators are running, the new items are excluded from the process. The values are taken when the callbackFunc visits the item. The length of the array is the most important because if there are multiple additions and removal from the array, if an item is found in the index it will be processed, else it will not be.

console.table(arr) – Displays the array in a tabular format.

arr.findIndex(testFunc, this) - Returns the index of the first found item, else -1
testFunc(item, index?, array?)
arr.forEach(callbackFunc, this) - Loops through all the items of the array
callbackFunc(item, index?, array?)

There is no way to stop a forEach loop

iterator = arr.keys() - Returns an Array Iterator of all the indexes
iterator = arr.values() - Returns an Array Iterator of all the values
console.log(iterator.next().value)

arr.map(callbackFunc, this?) – Returns a new Array with the callbackFunc applied on each item. The original array remains unchanged.
callbackFunc(item, index?, array?)

arr.reduce(reducerFunc, initialValue?) - Returns the value after all the reduce is done
reducerFunc(totalValue, currentValue, index?, array?)

Lot of info – https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

arr.reduceRight(reducerFunc, initialValue?) - Same as reduce(), only run from the lastItem to the firstItem

You can read more on JavaScript here.

Leave a Reply