015_Deep Dive into Array Method

Working with mutator and immutator array methods:

  • push,pop,shift,unshift,splice,isArray and soon are mutator methods 
  • slice,join,concat, and other soon are immutator methods        


Adding an Item to an Array

  • If we want to add a new item to the array, we can assign a value to the next index.

Adding Data to an array

push and pop concept : DataStructure Stack

push : Adding element at the end of array

const hobbies = ['cooking', 'hiking', 'playing']
hobbies.push('watching')
console.log(hobbies);
hobbies.pop()
console.log(hobbies);

// pop : removing the element based on LIFO concepts


// shift and unshift concepts

// unshift: add the element at the begging and shifting the element from left
to right

hobbies.unshift('dancing')
console.log(hobbies);

// delete 0 index value and shift 1-index value to 0-index value form right to
left
hobbies.shift()
console.log(hobbies);

// points to remember : Because of the fact that unshift and shift
are much slower as shift affect all the element in an array
which implies that performance wise slower than push pop method.




Removing an Item from an Array
  • When we want to remove a specific item from an array, we use the splice() method
  • only available on real array
  • takes two arguments only
1st version:
                   splice(start index , delete count from that index);

const gagets = ['mobile', 'camera', 'ipad', 'iphone', 'laptop'];
// gagets.splice(0, 1);
console.log(gagets);

2nd version:
        Splice(startindex,deletecountfrom that index,addelementfrom that index)

gagets.splice(0, 1, 'telescope');
console.log(gagets);


// works with negative indexes

// Note : not allowed for real array



Slice method():

  • returns new brand array and also nice way of copying array.
  • syntax : slice(start , end) // end is excluded
const testResult = [1, 2, 3, 4, 5.5, 6, 7, 8];
const outputResult = testResult.slice(0, 5);
console.log(outputResult);

  • can be used in select range.
  • using old array and creating new array.

// examples with over range

const testResult = [1, 2, 3, 4, 5.5, 6, 7, 8];
const outputResult = testResult.slice(0, 10);
console.log(outputResult);


// only start index : from current index to last index

const outputResult = testResult.slice(2);

Looping Through an Array

We can loop through the entirety of the array with the for keyword, taking advantage of the length property. In this example, we can create an array of shellfish and print out each index number as well as each value to the console.

// Create an array of shellfish species
let shellfish = [
    "oyster",
    "shrimp",
    "clam",
    "mussel",
];

// Loop through the length of the array
for (let i = 0; i < shellfish.length; i++) {
  console.log(i, shellfish[i]);
}
Output
0 'oyster' 1 'shrimp' 2 'clam' 3 'mussel'

We can also use the for...of loop, a newer feature of JavaScript.

// Create an array of aquatic mammals
let mammals = [
    "dolphin",
    "whale",
    "manatee",
];

// Loop through each mammal
for (let mammal of mammals) {
    console.log(mammal);
}
Output
dolphin whale manatee

 Note : The for...of loop does not retrieve the index number of the elements in the array,

 but it is generally a simpler, more concise way to loop through an array.

Using loops is extremely useful for printing out the whole value of an array, such as when displaying the items from a database on a website.


concat():  let testResults = [1, 2, 3, 4, 5, 6, 7, 8];


storedResults = testResults.concat([]);
console.log(storedResults); // concats pull out element of array you are
passing here and return new array
  • copies new array hence creating new place in memory.


   Reteriving index in javascript: indexof() and last index of()


const testResult = [1, 2, 34, 5, 6, 7, 8, 9, 6]
console.log(testResult.indexOf(3)) // returns -1

console.log(testResult.indexOf(34)) // return index 2

console.log(testResult.indexOf(6)) // return index 4    

Note : searching from the left to right and if more than one times with same value,it 

stop after finding first match .

  • works well for primitive value but not for reference value.
  • if no match found returns -1 


lastIndexOf()

The lastIndexOf() method returns the index number of the last instance of an element.

We can test on the same example from indexOf(), which includes barracuda twice.

let fish = [ "piranha", "barracuda", "koi", "barracuda" ];

// Find the last instance of an element
fish.lastIndexOf("barracuda");
Output
3

lastIndexOf() will search the array starting from the end and return the first index number it finds


Arrays are similar to strings, in that they both consist of a sequence of elements that can be accessed via index number. However, it is important to remember that strings are an immutable datatype, meaning they cannot be changed. Arrays, on the other hand, are mutable, which means that many array methods will affect the original array, not a copy of the array.

Note: Array methods are properly written out as Array.prototype.method(), as Array.prototype refers to the Array object itself. For simplicity, we will simply list the name as method().

isArray()

Before we get into mutator methods, let’s look at the isArray() method to test whether objects are arrays. This is a Boolean method that returns true if the value of a variable is equal to an array. If the object is not an array, this method returns false.

let fish = [ "piranha", "barracuda", "koi", "eel" ];

// Test if fish variable is an array
Array.isArray(fish);
Output
true

The isArray() method is useful because the typeof operator we would normally use for testing returns object when used with arrays, and sometimes knowing the distinction between an object and an Array object is necessary.

Note that isArray() is written differently from most array methods, with the array variable being provided as an argument to the method.


reverse()

The reverse() method reverses the order of the elements in an array.

let fish = [ "piranha", "barracuda", "koi", "eel" ];

Using reverse(), the last element will be first, and the first element will be last.

// Reverse the fish array
fish.reverse();

fish;
Output
[ 'eel', 'koi', 'barracuda', 'piranha' ]

The reverse() array method has no parameters.

fill()

The fill() method replaces all the elements in an array with a static value.

let fish = [ "piranha", "barracuda", "koi", "eel" ];

In the fish array, we have four items. Let’s apply fill().

// Replace all values in the array with "shark"
fish.fill("shark");

fish;
Output
[ 'shark', 'shark', 'shark', 'shark' ]

All four items in the array have been replaced with the same value, "shark"fill() also takes optional arguments of start and end points.

fish.fill("shark", 1) // > [ 'piranha', 'shark', 'shark', 'shark' ]
fish.fill("shark", 1, 3); // > [ 'piranha', 'shark', 'shark', 'eel' ]

Using fill() we can replace one or more elements in an array with a static value


join()

The join() method converts all the elements of an array into a new string.

let fish = [ "piranha", "barracuda", "koi", "eel" ];

If no argument is given, the output of join() will be a comma-separated string with no extra whitespace.

// Join the elements of an array into a string
let fishString = fish.join();

fishString;
Output
'piranha,barracuda,koi,eel'

In order to include whitespace or another separator, you can add a string of your separator as a parameter to the join() method. This parameter will contain the separator you would like between each array element.

// Join the elements of an array into a string
let fishString = fish.join(', ');

fishString;
Output
'piranha, barracuda, koi, eel'

In the above example, writing ', ' with whitespace separated the array items in a more readable fashion. An empty string provided as an argument will remove the default commas completely.


let instruments = ['box', 'pencil', 'rubber']
let result = instruments.join('/');
console.log(result);

  • using seperator as blackslash 



sort()

The sort() method sorts the elements in an array based on the first character in the element. In the case that the first character is identical, it will continue down the line and compare the second character, and so on.

By default, sort() will alphabetize an array of strings that are all either uppercase or lowercase.

let fish = [ "piranha", "barracuda", "koi", "eel" ];

// Sort items in array
fish.sort();

fish;
Output
[ 'barracuda', 'eel', 'koi', 'piranha' ]

Since sort() is based on the first unicode character, it will sort uppercase items before lowercase.

Let’s modify our original array so that one of our strings begin with an uppercase letter.

let fish = [ "piranha", "barracuda", "Koi", "eel" ];

fish.sort();

fish;
Output
[ 'Koi', 'barracuda', 'eel', 'piranha' ]

Numbers come before both uppercase and lowercase characters.

We can again modify the array to include a number in one of the string items.

let fish = [ "piranha", "barracuda", "Koi", "1 eel" ];

fish.sort();
Output
[ '1 eel', 'Koi', 'barracuda', 'piranha' ]

sort() will not sort an array of numbers by size by default. Instead, it will only check the first character in the number.

let numbers = [ 42, 23, 16, 15, 4, 8 ];

numbers.sort();
Output
[ 15, 16, 23, 4, 42, 8 ]

In order to sort numbers properly, you could create a comparison function as an argument.

// Function to sort numbers by size
const sortNumerically = (a, b) => {
  return a - b;
}

numbers.sort(sortNumerically);
Output
[ 4, 8, 15, 16, 23, 42 ]

The sortNumerically comparison function allowed us to sort as intended. sort() will apply the change to the original array.


Wap to reverse a number:

function reverse_a_number(num) {
num = num + "";
return num.split("").reverse().join("");
}
console.log(reverse_a_number(32243)); // 34223

The split() method is used to split a String object into an array of
strings by separating the string into substrings.
The reverse() method is used to reverse an array in place.
The first array element becomes the last and the last becomes the first.
The join() method is used to join all elements of an array into a string.

Comments

Popular posts from this blog

JavaScript — Double Equals vs. Triple Equals - weird things on JavaScript

06_Understanding Execution Context and Execution Stack in Javascript

Creating and inserting element- part-2