Capture Collection Of Data With Arrays in javaScript.

ยท

8 min read

Capture Collection Of Data With Arrays in javaScript.

Introducing Arrays

Array is our first Data Structure.

Most of the time in real world our data is complicated , it consist of pisces like numbers , strings & booleans but usually we have more than one piece of information and the often related to each other. So this is where Data Structure Comes in.

Arrays

Arrays are ordered collection of values. all of different values like strings,numbers,booleans things like null and undefined Arrays collect them in one structure in one collection and its ordered for ex:

  • List of Comment on IG Post.
  • Songs in Playlist
  • Level of player in game

on their own Arrays don't do much unless we put information in it. so they collect all primitive types of data also another Arrays and Objects.

Creating Arrays

// To make an Empty Array
let student = [];

// An Array Of String
let student = ['Karan', 'Vijay', 'Anurag', 'Hitesh'];

// An Array Of Numbers
let serialNumbers = [11,12,13,14,15];

// A Mixed Array
let details = [12,'Hero',false,null];

Array Are Indexed

The next thing to know about Arrays are they Indexed, Every Item in array have corresponding index and that index dictate the order, so something is index 0 it will be the first item in array and indexed 1 will be the 2nd item in Array. lets see in Example.

let colors = ['red','green','blue','orange'];
colors[0]; // Output will be red, because red has indexed of 0.
colors[3]; // Output will be orange, because orange has indexed of 3.
colors[4]; // Output will be undefined , because there is no item on 4.

Array also have length property sometimes we get a huge number of data through apis in our array so in that case array.length property help us to find how many items we have in our Array. for example.

let manyNums [11,34,55,66,223,42,45,12,67,234,78,23,77,224,899,75,7,91,45,67,89,23,57,135,45,12,67,234,78,23];

manyNums.length; // 30 items we are having in manyNums Array.

so great now we can access data we can read it out next we are going to see About modifying Data.

Modifying Arrays

Now we have seen how to create Arrays how to access individual items using indexed now let's talk about changing them.

we can use exact same syntax we already seen we use [index] and sq brackets but we can assign new value and that value will replace original value that index had. for example

let colors = ['red','green','blue','orange'];
colors[0] = 'orangered'; // now red is replaced by orangered
colors = ['orangered','green','blue','orange'];

colors[4] = 'Brown'// 'Brown' will added and it will not give us undefined.

Arrays are Mutable we can change them whenever we want.

Arrays Method

let's dive into first four Arrays Methods , there are more but first four are grouped together for a reason. They are really commonly used , and they all have to do with either adding or removing elements from an Array.

Array Methods

  • Push - add element to end
  • Pop - remove element from an end
  • Shift - remove element from start
  • Unshift - add element to start

Lets understand throughout the examples.

- Push - add element to end

let songs = ["Judas", "Thunder","August","Hold Me"];
songs.push("Feels Like"); // Output will be  songs = ["Judas","Thunder","August","Hold Me","Feels Like"];
songs = ["Judas","Thunder","August","Hold Me","Feels Like"];

- Pop - remove element from an end

let songs = ["Judas", "Thunder","August","Hold Me"];
songs.pop(); // Output will be  songs = ["Judas","Thunder","August"];
songs = ["Judas","Thunder","August"];

- Shift - remove element from start

let songs = ["Judas", "Thunder","August","Hold Me"];
songs.shift(); // Output will be songs = ['Thunder','August','Hold Me'];
let songs = ["Thunder","August","Hold Me"];

- Unshift - add element to start

let songs = ["Judas", "Thunder","August","Hold Me"];
songs.unshift("Afraid"); // Output will be let songs = ["Afraid","Judas", "Thunder","August","Hold Me"];

More Array Methods ** - concat - Merge Arrays The Array.concat() Method used to merge two or more arrays. lets see in example

let array1 = ['a','b','c','d'];
let array2 = ['e','f','g','h'];
let array3 = array1.concat(array2); // array3 = ['a','b','c','d','e','f','g','h']

but the original arrays will be unchanged for example

console.log(array1) // output ['a','b','c','d'];
console.log(array2) // output ['e','f','g','h'];

- includes - looks for value in Array

includes is relatively simple, it is known as boolean method, it returns true or false. it takes the value and tell you weather that value is in that array or not.

let sayians = ['goku','vageta','gohan','trunks','goten'];
sayians.includes('vageta'); // Output will be true.
sayians.includes('Brolly'); // Output will be false.

- indexOf - return indexOf element so its search for value and return index of an element for example.

let drivers = ['Aman','Sahil','Pratik','Singha','Tarun','Rakesh'];
drivers.indexOf('Singha'); // Output will be 3.

// if we try to get item which is not present in array 
drivers.indexOf('Rajat') // Output will be -1

-reverse - reverse an Array

The reverse() method reverses an array. for example

const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// expected output: "array1:" Array ["one", "two", "three"]

const reversed = array1.reverse();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]

// Careful: reverse is destructive -- it changes the original array.
console.log('array1:', array1);
// expected output: "array1:" Array ["three", "two", "one"]

- join - create string from an Array

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.

const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// expected output: "Fire,Air,Water"

console.log(elements.join(''));
// expected output: "FireAirWater"

console.log(elements.join('-'));
// expected output: "Fire-Air-Water"

- slice - copy portion of an array

method slice is very useful one, it does it sound likes it takes portion of an Array and it makes new Array with it , it doesn't impact the original Array , but it allows you to select or copy part of an Array to new Array. lets take a look.

let animals = ['shark','salmon','whale','bear','lizard','tortoise'];
let swimmers = animals.slice(0,3); // ['shark','salmon','whale'];

console.log(animals.slice(2));
// expected output: Array ["whale", "bear", "lizard","tortoise"];

//quick way to make an copy of an array
let copy = animals.slice();
copy = ['shark','salmon','whale','bear','lizard','tortoise'];

- splice - remove/replace items

This method modifies the original array and returns the removed elements as a new array. How to remove array elements with splice() For example, suppose you have an array named months but you have some day names in the array as follows:

let months = ["January", "February", "Monday", "Tuesday"];

You can use the splice() method to remove the day names from the months method and add it to a new array at the same time:

let months = ["January", "February", "Monday", "Tuesday"];
let days = months.splice(2);

console.log(days); // ["Monday", "Tuesday"]

The splice() method needs at least one parameter, which is the start index where the splice operation starts. In the code above, the number 2 is passed to the method, which means splice() will start removing elements from index 2.

You can also define how many elements you want to remove from the array by passing a second number argument known as removeCount. For example, to remove only one element, you can pass the number 1 like this:

let months = ["January", "February", "Monday", "Tuesday"];
let days = months.splice(2, 1);

console.log(days); // ["Monday"]
console.log(months); // ["January", "February", "Tuesday"]

When you omit the removeCount parameter, splice() will remove all elements from the start index to the end of the array.

How to remove and add array elements with splice() The method also allows you to add new elements right after the delete operation. You just need to pass the elements you want to add to the array after the delete count.

The full syntax of the splice() method is as follows:

Array.splice(start, removeCount, newItem, newItem, newItem, ...)

The following example shows how you can remove "Monday" and "Tuesday" while adding "March" and "April" to the months array:

let months = ["January", "February", "Monday", "Tuesday"];
let days = months.splice(2, 2, "March", "April");

console.log(days); // ["Monday", "Tuesday"]
console.log(months); // ["January", "February", "March", "April"]

How to add new array elements without removing any elements Finally, you can add new elements without removing any by passing the number 0 to the removeCount parameter. When no elements are removed, the splice method will return an empty array. You can choose whether to store the returned empty array to a variable or not.

The following example shows how you can add a new element "March" next to "February" without deleting any elements. Since the splice() method returns an empty array, you don't need to store the returned array:

let months = ["January", "February", "Monday", "Tuesday"];
months.splice(2, 0, "March");

console.log(months); 
// ["January", "February", "March", "Monday", "Tuesday"]

- sort - sort an Array so Array.sort() sound simple , its sounds like its going to take the data and sort it. that is what it saids out to do , but the way it do might surprise you. lets try to understand by examples

let womenNames = ['priyanka','jonita','kareena','johana','anagha'];
womenNames.sort(); // Output  ['anagha', 'johana', 'jonita', 'kareena', 'priyanka']

its worked , alphabetically its correct , and original womenNames Array got mutated in place

womenNames = ['anagha', 'johana', 'jonita', 'kareena', 'priyanka'];

but where it gets tricky it get tricky with Numbers for example

let numbers = [34,6888,99,65,12,67];

numbers.sort() // [12, 34, 65, 67, 6888, 99]

and you can see what we get here [12, 34, 65, 67, 6888, 99] . what is happening here that it's not sorting base on numeric value it is converting every single value to string and then comparing their character code UTF-16 CODE behind the scene. so this is the default behaviour of Array.sort() . btw almost no one use this method instead they do they pass in compare function. you can read here for more details

so those are some of the most common methods for Array you can see. there are other but that will cover later in next blog. i hope these will help you .

Thanks for Reading this Blog. if you like it leave a like, comment. okay that's it i am going away bye ๐Ÿ‘‹๐Ÿป.

Let's connect on Twitter || Linkedin || Instagram โค๏ธ ๐Ÿ™‹๐Ÿปโ€โ™‚๏ธ

ย