Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 24, 2021 12:29 pm GMT

JavaScript Arrays and its Methods.

Abstract

JavaScript provides a data type specifically for storing an ordered collection of values. It is called an array and is written as a list of values between square brackets, separated by commas.
Arrays are zero-indexed. It can hold many values under a single name, and you can access the values by referring to an index number.

Scope of Article

This article defines a special type of data structure in JavaScript named Array and a number of its properties that hold function values.

Definition

An array is like a big container into which we can store elements of any type and then later reference them.
An Array is written as a list of values between square brackets, separated by commas.

const friends= ["Mike"," Steven","Elena","Bonnie"];console.log(friends);

We can store values of any type like this:

let arr= ["Orange", {name: "Insha"}, true, function(){alert('hello');}];

JavaScript, Arrays are zero-indexed. That basically means the first element of an array is at position 0.

You might be thinking How to access an Array Element?

You can easily access an array element by referring to the index number.

Lets suppose we want to access elements of the friends array. This is how well do that:

console.log(friends[0]); // Mikeconsole.log(friends[2]); // Elena

Note- The notation for getting at the elements inside an array also uses square brackets.

There are multiple ways to manipulate an array like :

-We can change the elements of an array

friends[2]= "John";console.log(friends); // ["Mike"," Steven","John","Bonnie"];

-Or add a new one to the array:

friends[4]= "Insha"; 

The length property of an array tells us how many elements it has.

let fruits = ["Apple", "Orange", "Plum"];console.log( fruits.length ); // 3

Moving forward to Array Methods.

Array methods are built-in functions in JavaScript that you apply to arrays. Each method has a particular function that changes or manipulates the array.

Methods to add elements.

Push - It adds an element to the end of an array.

const friends= ["Mike"," Steven","Elena","Bonnie"];friends.push("John");

push() is basically a function as we can see the parenthesis(). Since push is a function here so it can even return something Right?

As we pass arguments in a function we did the same here. We passed John as an argument and it returned a value here and that is the length.

To see if it works. Lets log in to the console:

console.log(friends);console.log(friends.length); //5

Unshift - It adds the element to the beginning of the array.

friends.unshift("Ronnie");

And if we log in to the console well see that Ronnie is added to the beginning of the friends array.

Methods to Remove Elements:

Pop- It removes the last element of an array.

friends.pop();

In the pop() method, we dont need to pass any argument.
If we do this twice it will remove 2 elements from the end.

shift- It removes the first element of an array.

friends.shift();

Note- pop() and shift() method does not return the length of an array instead they return the element thats removed.

slice- It selects a chunk of an array & returns a NEW array with a copy of all elements selected from the start index to the end index(not including the end).
It doesnt mutate the original array.

Let arr= [a, b, c, d, e];console.log(arr.slice(2,4)); // ["c", "d"]console.log(arr.slice(2)); //  ["c", "d", "e"]

Note- When the end parameter is not declared, it copies all the elements from the starting index till the end.

We can also use the slice method to create a shallow copy of an array (same as the spread operator).

console.log(arr.slice());

splice- slice() and splice() methods are exactly the same. The only fundamental difference is that the splice method does mutate the original array.
It can be used to remove, replace, or add new elements to the array.

console.log(arr.splice(1,2)); // ["a" , "d"]

Here, In the above example, we specify two arguments that are the starting index and the deleteCount. What it does is select the element from index 1 and remove the next 2 elements.

console.log(arr.splice(2)); // ["c", "d", "e"]console.log(arr); // ["a" , "b"]

We see the original array is mutated and the extracted element is gone away.

One pretty use case of the splice method is to simply remove the last element of the array.

arr.splice(-1);console.log(arr);  // ["a", "b", "c", "d"]

The splice method is also able to insert the elements without any removals. For that, we need to set the deleteCount to 0.

Lets see it in action.

Let arr= [ "I", "am", "a", "Developer"];arr.splice(3, 0, "from" , "India");console.log(arr); 

What happened here is that from index 3 no elements are deleted instead the two new elements are inserted.

reverse- It reverses an array; the first element becomes last, and the last becomes first. It changes the original array and returns the reversed array.

const arr2= ["j", "i", "h", "g", "f];console.log(arr2.reverse()); // ["f", "g", "h", "i", "j];

It does mutate the original array and also returns the array arr2 after the reversal.

concat- It merges two arrays into a new array.

const letters= arr.concat(arr2);console.log(letters); 

Does this look familiar to you?

Let me tell you it is similar to something like :

console.log([...arr, ...arr2]);

Earlier we did the same using the spread operator. But after knowing the array methods we can use them to our convenience.

concat() doesnt mutate the original array.

join - The join() method returns an array of elements as a string either separated by commas or a specified separator.

It doesnt mutate the original array.

console.log(letters.join('-')); // a-b-c-d-e-f-g-h-i-j

forEach- It is used for looping arrays. forEach is a Higher-Order Function that requires a callback function to tell it what to do.

forEach() will iterate over the array and in each iteration, itll execute the callback function. It passes the current element, the index, and the entire array that were looping.

const movements= [200, 450, -400, 3000, -650, -130, 70, 1300];movements.forEach(function(movement, index, array){if(movement > 0) {console.log(` Movement${i+1}: You deposited ${movement}`);} else{console.log(`Movement${i+1}:You withdrew ${movement}`)'}});

Just notice the order of the parameters that we passed in the callback function. Here the first value is the current element, and the second one is the index.

Note- The break and the continue method doesnt work in forEach.

map- The map() method does return a brand new array and calls the function for each element in the array.

const eurToUSD= 1.1;const movementUSD= movements.map(function(mov){return mov * eurToUSD;});console.log(movements);console.log(movementsUSD);

It doesnt mutate the original array.

filter - The filter() method is used to filter elements of an array that satisfy a certain condition.

const deposits= movements.filter(function(mov){return mov > 0;});console.log(deposits); //[200, 450, 3000, 70, 1300]

Each element of the array is passed to a callback function that either returns true or false. If the callback returns true for a specific element, that element is added to the new array.

reduce- It simply reduces the array into a single element. It passes the return value of the previous element in the callback function.

reduce() also l0op over the array and calls the callback function in each iteration.

To put it simply, it kind of adds the result of the previous value to the current value.

const movements= [200, 450, -400, 3000, -650, -130, 70, 1300];const balance = movements.reduce(function(accumulator, currentValue, i, arr){return accumulator + currentValue ;},0); // 0 is the initial value of the accumulator in the forst loop iterationconsole.log(movements); // 3840

Accumulator keeps accumulating the value that we ultimately want to return.

find - This method is used to retrieve an element of the array based on a certain condition.

const firstWithdrawal= movements.find(mov=> mov<0);console.log(firstWithdrawal); // -450

You may find it similar to the filter() method but theres some fundamental difference between these two:

filter() returns all the elements that match the condition while the find() method only returns the first one.
The filter() method returns a new array while find() only returns the element itself and not an array.

findIndex- It returns the index of the found element in the array that satisfies a certain condition. and not the element itself.

Both the find() and the findIndex() method get access to the current Index and the current entire array.

const num= [1,2,3,4,5,6,7,8];//find the index of the first element that is divisible by 2Let indexNum= num.findIndex(num=> num% 2 === 0);console.log(indexNum); // returned the index [1] = 2

includes- This method checks for equality. That means if the array includes the item which is passed to the method it returns true or else false.

const num= [1,2,3,4,5,6,7,8];let numIncludes= num.includes(4);console.log(numIncludes); //true

some- The includes() and some() methods are almost similar. The only difference is that the includes method checks for equality while some method checks a given condition and if its true it returns true or else false.

const movements= [200, 450, -400, 3000, -650, -130, 70, 1300];const anyDeposits= movements.some(mov=> mov>0);console.log(anyDeposits); //true

Note- Every element isn't required to pass the callback; if one element returns true, some() method returns true.

every- The every() method returns true only if all of the elements in the array satisfy the condition that we passed into the callback function.

const movements= ["200", "450", "-400", "3000", "-650", "-130", "70", "1300"];const anyDeposits= movements.every(mov=> mov>0); console.log(anyDeposits); //false

In this case, it returns false because all the elements in the movements array isnt a positive number.

sort- It sorts the elements in an array, then returns it. The sort() method keeps looping over the array and applying the callback function until everything is in ascending order.

const owners= ['Zach', 'Emily', 'Jack', 'Demon'];console.log(owners.sort());console.log(owners); // ['Demon', 'Emily', 'Jack', 'Zach']

sort() method first converts the elements into strings, then compares its code. This actually mutates the original array and returns the sorted array.

toString- It simply converts an array into a string.

const arr= ['Hey' 'Developer'];let arrToString= arr.toString();console.log(arrToString);

flat- The flat() method simply flattens the nested array.

const arr= [[1,2,3], [4,5,6], 7,8];console.log(arr.flat()); //[1,2,3,4,5,6,7,8]

Here we see the flat method removed the nested array and flattened it to one level.

But what if we have some complex nested array?

We use the depth argument in such cases.

const arrDeep= [[1,2],3], [4,[5,6]], 7,8];console.log(arrDeep.flat(2)); //[1,2,3,4,5,6,7,8]

flatMap- Exactly the same as flat() method. The only difference is that it essentially combines a flat() and a map() method into just one method which is actually good for performance.

Note- flatMap() needs to receive the exact callback as the map does.

let arr1 = [1, 2, 3, 4];arr1.map(x => [x * 2]);// [[2], [4], [6], [8]]arr1.flatMap(x => [x * 2]);// [2, 4, 6, 8]

Summary

-An array is like a big container into which we can store elements of any type and then later reference them.

-Array methods are built-in functions in JavaScript that we apply to arrays.

-Array methods are useful in order to mutate or manipulate the array.


Original Link: https://dev.to/insha/javascript-array-and-its-methods-432k

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To