Array and It's method   (javascript)

Array and It's method (javascript)

What is Array?

Array is a Special variable, Which can hold more then one value. In javascript Array are not a primitives but objects to Understand we have some core Characteristics of It.

  • JavaScript Arrays are resizable and can contain a mix of different Data types ( This can be Avoided by using of typed Arrays instead)
  • Javascript Arrrays are not associative Arrays and so Array element cannot be accesssed usijng arbitrary Strings as indexes, but must be accessed using nonnegative integers (or their respective string form ) as indexes

error

console.log(arr.0);

run

 console.log(arra[0])
  • JavaScript Arrays are Zero-indexed, It meain the First Element of an array is at index 0, the second is at index1, and so on and last elment is at the value of arrasy's lenght property minus 1.
    const Arra = [1,2,3,4,5,6,7,8,9,] 
    indexing   value= position :- 1=0,  2=1,  3=2 ,  4=3  ...... etc
    
  • Javascript Array-copy operations Create Shallow copies ( All standard built-in copy operations with any javascript object create shalow copies rather than Deep copies ).
//it is a  Shallow Copy due to  fact that Array are Reference type  in Nature

let Array1 = {name : "shivam pandey"};
let Array2 = Array1;

console.log(Array1);
//outcome :-"shivam pandey"
console.log(Array2);
//outcome :-"shivam pandey"


Array2.name ="Shivam"

console.log(Array1);
//outcome :-"Shivam"
console.log(Array2);
//outcome :-"Shivam"

array.PNG

Why Is this happening ? When we change something copyed element the source also changed

It is due to fact that this is a Shallow copy and not a deep one. As we Said Array's are Reference Type in nature so what is happening here is the first Decleration is creating a array object in the memory location and in the Second Array We are refereing the to that location so when we change the Second Array it's changes the array which was located at the first Array location

How to over come This Shallow Copies

There is Two Way's to over this Situation first one being using (...) spread operator ( it have it's con's )

let Array1 = { name: "shivam pandey" };
let Array2 = { ...Array1 };

console.log(Array1);
//outcome :-"shivam pandey"
console.log(Array2);
//outcome :-"shivam pandey"

Array2.name = "Shivam";

console.log(Array1);
//outcome :-"shivam pandey"
console.log(Array2);
//outcome :-"Shivam"

array2.PNG

but There is An Issue With This type of use it's looks good on surface but inside this have a hole or un-expected event by using a spread operator we can create a different look a like array but it's create a event

let Array1 = {
  name: "shivam pandey",
  skills: { primary: "Array artical", Secondary: "Array Shallow copy" },
};
let Array2 = { ...Array1 };

console.log(Array1);
/*outcome :-{
  name: 'Shivam',
  skills: { primary: "Array artical", Secondary: 'Array Shallow copy' }
}
*/
console.log(Array2);
/*outcome :-{
  name: 'Shivam',
  skills: { primary: "Array artical", Secondary: 'Array Shallow copy' }
}
*/

Array2.name = "Shivam";
Array2.skills.primary = "Development First";

console.log(Array1);
/*outcome :-{
  name: 'Shivam',
  skills: { primary: 'Development First', Secondary: 'Array Shallow copy' }
}
*/
console.log(Array2);
/*outcome :-{
  name: 'Shivam',
  skills: { primary: 'Development First', Secondary: 'Array Shallow copy' }
}
*/

it will not work on multi-object array

So What can we Do to make it a seperate array it's self

for to get best way to copy a array in javascript would be JSON.parse(JSON.stringify(arrayname));

let Array1 = {
  name: "shivam pandey",
  skills: { primary: "Array artical", Secondary: "Array Shallow copy" },
};
let Array2 = JSON.parse(JSON.stringify(Array1));

console.log(Array1);
/**
 *
 * outcome: {
 *name: 'shivam pandey',
 *skills: { primary: 'Array artical', Secondary: 'Array Shallow copy' }
 *   }
 */
console.log(Array2);
/**
 *
 * outcome: {
 *name: 'shivam pandey',
 *skills: { primary: 'Array artical', Secondary: 'Array Shallow copy' }
 *   }
 */

Array2.name = "Shivam";
Array2.skills.primary = "Development First";

console.log(Array1);

/**
 *
 * outcome: {
 *name: 'shivam pandey',
 *skills: { primary: 'Array artical', Secondary: 'Array Shallow copy' }
 *   }
 */

console.log(Array2);

/* outcome :-{
 * name: 'Shivam',
 * skills: { primary: 'Development First', Secondary: 'Array Shallow copy' }
 *
 */

It is best practice to use JSON.parse( JSON.stringfy(arrayname) ); to copy an array Now That we undstand the Characterstics of Array Let's understand the Method of Array

Method Of Array

Method Definition is shorter syntax for defining a function property in an object initilizer Array have many Method's to Work with which help us to Interact with Data which is stored in it There are the some of the following Arrya method in javascript ( most Comman ).

javaScript Array Length()

The length property returns or sets the number of elments in an array


let city = ["California", "Barcelona", "Paris", "Kathmandu"];

// find the length of the city array
let len = city.length;
console.log(len);

// Output: 4

javaScript lenght Syntax :- The Syntax to access the length Property is

arr.lenght

Here, arr is an array.

Example 1: Finding Number of Elements in an Array

let city = ["California", "Barcelona", "Paris", "Kathmandu"];

// find the length of the city array
let len = city.length;
console.log(len);

// Output: 4


JavaScript Array reverse()

The reverse() method returns the array in reverse order

let numbers = [1, 2, 3, 4, 5];

// reversing the numbers array
let reversedArray = numbers.reverse();

console.log(reversedArray);

// Output: [ 5, 4, 3, 2, 1 ]

reverse() syntax :- The Syntax of the reverse() method is

arr.reverse()

here arr is an array.

Example 1: Finding Number of Elements in an Array

let languages = ["JavaScript", "Python", "C++", "Java", "Lua"];

// reversing the order of languages array
let reversedArray = languages.reverse();

console.log("Reversed Array: ", reversedArray);

// modifies the original array
console.log("Original Array: ", languages);


JavaScript Array sort()

The sort() method sorts the items of an array in a specific order (ascending or decending).

Example

let city = ["California", "Barcelona", "Paris", "Kathmandu"];

// sort the city array in ascending order
let sortedArray = city.sort();
console.log(sortedArray);

// Output: [ 'Barcelona', 'California', 'Kathmandu', 'Paris' ]

sort() Syntax :- The Syntax of the sort() method is

ara.sort(comparefuction)

Here, arr is an array.


Javascript Array join()

The join() method returns a new string by concatenating all of the elements in an array, separated by a specified separator.

Example

let message = ["JavaScript", "is", "fun."];

// join all elements of array using space
let joinedMessage = message.join(" ");
console.log(joinedMessage);

// Output: JavaScript is fun.

join() Syntax :- The syntax of the join() method is

arr.join(separator)

Here, arr is an array.


Javascript Array toString()

The toString()method returns a string formed by the elements of the given array.

Example

// defining an array
let items = ["JavaScript", 1, "a", 3];

// returns a string with elements of the array separated by commas
let itemsString = items.toString();

console.log(itemsString);

// Output: 
// JavaScript,1,a,3

toString() Syntax :- The syntax of the toString() method is:

arr.toString()

Here, arr is an array.


JavaScript Array push()

The push() method adds zero or more elements to the end of the array.

Example

let city = ["New York", "Madrid", "Kathmandu"];

// add "London" to the array
city.push("London");

console.log(city);

// Output: [ 'New York', 'Madrid', 'Kathmandu', 'London' ]

push() Syntax:- The syntax of the push() method is:

arr.push(element1, element2, ..., elementN)

Here, arr is an array.


JavaScript Array pop()

The pop() method removes the last element from an array and returns that element.

Example

let cities = ["Madrid", "New York", "Kathmandu", "Paris"];

// remove the last element
let removedCity = cities.pop();

console.log(cities)         // ["Madrid", "New York", "Kathmandu"]
console.log(removedCity);   // Paris

pop() Syntax:- The syntax of the pop() method is:

arr.push(element1, element2, ..., elementN)

Here, arr is an array.


JavaScript Array shift()

The shift() method removes the first element from an array and returns that element.

Example

let languages = ["English", "Java", "Python", "JavaScript"];

// removes the first element of the array
let first = languages.shift();
console.log(first);
console.log(languages);

// Output: English
//         [ 'Java', 'Python', 'JavaScript' ]

shift() Syntax:- The syntax of the shift() method is:

arr.pop()

Here, arr is an array.

JavaScript Array unshift()

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

Example

let languages = ["Java", "Python", "C"];

// add "JavaScript" at the beginning of the array
languages.unshift("JavaScript");
console.log(languages);

// Output: [ 'JavaScript', 'Java', 'Python', 'C' ]

unshift() Syntax:- The syntax of the unshift() method is:

arr.unshift(element1, element2, ..., elementN)

Here, arr is an array.


JavaScript Array concat()

The concat() method returns a new array by merging two or more values/arrays.

Example

let primeNumbers = [2, 3, 5, 7]
let evenNumbers = [2, 4, 6, 8]

// join two arrays 
let joinedArrays = primeNumbers.concat(evenNumbers);
console.log(joinedArrays);

/* Output:
[
  2, 3, 5, 7,
  2, 4, 6, 8 
]
*/

concat() Syntax:- The syntax of the concat() method is:

arr.concat(value1, value2, ..., valueN)

Here, arr is an array.

JavaScript Array splice()

The splice() method returns an array by changing (adding/removing) its elements in place

Example

let prime_numbers = [2, 3, 5, 7, 9, 11];

// replace 1 element from index 4 by 13
let removedElement = prime_numbers.splice(4, 1, 13);
console.log(removedElement);
console.log(prime_numbers);

// Output: [ 9 ]
//         [ 2, 3, 5, 7, 13, 11 ]

spice() Syntax:- The syntax of the splice() method is:

arr.splice(start, deleteCount, item1, ..., itemN)

Here, arr is an array.


JavaScript Array indexOf()

The indexOf() method returns the first index of occurance of an array element, or -1 if it is not found.

Example

let languages = ["Java", "JavaScript", "Python", "JavaScript"];

// get the index of the first occurrence of "JavaScript"
let index = languages.indexOf("JavaScript");
console.log(index);

// Output: 1

indexOf() Syntax:- The syntax of the indexOf() method is

arr.indexOf(searchElement, fromIndex)

Here, arr is an array.


JavaScript Array lastIndexOf()

The lastIndexOf() method returns the index of the last occurrence of a specified element in the array.

Example

let priceList = [10, 8, 2, 31, 10, 31, 65];

// finding the index of the last occurence of 31
let lastIndex = priceList.lastIndexOf(31);

console.log(lastIndex); 

// Output: 5

lastIndexOf() Syntax:- The syntax of the lastIndexOf() method is:

arr.lastIndexOf(searchElement, fromIndex)

Here, arr is an array.


JavaScript Array map()

The map() method creates a new array with the results of calling a function for every array element.

Example

let numbers = [2, 4, 6, 8, 10];

// function to return the square of a number
function square(number) {
  return number * number;
}

// apply square() function to each item of the numbers list
let square_numbers = numbers.map(square);
console.log(square_numbers);

// Output: [ 4, 16, 36, 64, 100 ]

map() Syntax:- The syntax of the map() method is:

arr.map(callback(currentValue), thisArg)

Here, arr is an array.

Javascript Array copyWithin()

The copyWithin() method copies array elements from one position to another in the given array.

Example

let words = ["apple", "ball", "cat", "dog"];

// copies element from index 0 to index 3 
words.copyWithin(3, 0);

// modifies the original array 
console.log(words);

// Output: 
// [ ''apple'', ''ball'', ''cat'', ''apple'' ]

copyWithin() Syntax:- The syntax of the copyWithin() method is:

arr.copyWithin(target, start, end)

Here, arr is an array.