Understanding Arrays in JavaScript 🕹️

Understanding Arrays in JavaScript 🕹️

A brief guide for arrays in JavaScript.

·

11 min read

If you understand Hindi

Let's start the blog 🎯🎯🎯🎯

🤔What are Arrays?

Arrays are simply lists. An array is an object which is used to store multiple values with their indexes in a single variable.

The values inside an array are known as Elements.

🍌Why do we need it?

Let’s suppose you are going to a supermarket to buy fruit. You want to declare a variable in JavaScript which stores the name of the fruit you have bought, and with that store, you also want to store which fruit you have bought in which order. Eg: You first bought oranges, then apples, then bananas. So how will you tackle this problem?

🥳You can create an array for that.

// 👇 array with Element --> 'oranges', 'apples', 'bananas'
const fruits= ['oranges', 'apples', 'bananas']

console.log(fruits)

/*
Output
--> [ 'oranges', 'apples', 'bananas' ]
*/

🏵️Understanding Arrays

Each element in an array has an index number. The catch here is that the index number starts from 0.

// 👇 array
const fruits= ['oranges', 'apples', 'bananas']

👆In the code, oranges will have 0 index numbers, apples will have 1 index number, and bananas will have 2 index numbers.

😏Spread Function in Arrays

The spread function works in arrays the same way it works in objects

const fruits = ['oranges', 'apples', 'grapes']

// 👇 ... will spread the elements of fruits in moreFruits
const moreFruits = ['bananas', 'watermelons', ...fruits]

console.log(moreFruits);

🔪Destructuring in Arrays

const fruits = ['oranges', 'apples', 'grapes']

const [oranges, apples, grapes] = fruits;

console.log(oranges, apples, grapes);

🫠Methods in arrays

BASIC1️⃣toString()

What if you want to convert your array into a string?

// 👇 array
const fruits= ['oranges', 'apples', 'bananas']

// 👇 toString() will convert array into a string
console.log(fruits.toString())

/*
Output
--> oranges,apples,bananas
*/

BASIC2️⃣join()

What if you want to print these fruit’s names and have a symbol between them?

// 👇 array
const fruits= ['oranges', 'apples', 'bananas']

// 👇 join() will put ' + ' between the elements of an array.
console.log(fruits.join(' + '))

/*
Output
--> oranges + apples + bananas
*/

BASIC3️⃣pop()

What if you want to remove the last element of the array?

// 👇 array
const fruits= ['oranges', 'apples', 'bananas']

// 👇 pop() will remove the last element from the array
fruits.pop()

console.log(fruits);

/*
Output
--> ['oranges', 'apples']
*/

BASIC4️⃣push()

What if you want to add a new element to your array

// 👇 array
const fruits= ['oranges', 'apples', 'bananas']

// 👇 push() will add a new element 'grapes' in the array
fruits.push('grapes')
console.log(fruits);

/*
Output
--> ['apples', 'bananas', 'grapes']
*/

🛑Notice: It is to be noticed that you can add multiple elements in the push() parameters.

// 👇 array
const fruits= ['oranges', 'apples', 'bananas']

// 👇 push() will add a new element 'grapes' in the array in the last
fruits.push('grapes', 'peaches')
console.log(fruits);

/*
Output
--> ['oranges', 'apples', 'bananas', 'grapes', 'peaches']
*/

BASIC4️⃣shift()

Imagine that you reach your home and your mother shouts at you that the fruit you bought first is not needed. Then what will you do

// 👇 array
const fruits= ['oranges', 'apples', 'bananas']

// 👇 shift() will remove the first element and shift all the other elements with a lower index
fruits.shift()
console.log(fruits);

/*
Output
--> ['apples', 'bananas']
*/

BASIC5️⃣unshift()

Now imagine that you forgot to bring a fruit which your girlfriend likes, now 🙄 what will you do

// 👇 array
const fruits= ['oranges', 'apples', 'bananas']

// 👇 unshift() will add a new element 'strawberries' as the first elemtn and shift all the other elements to a higher index number
fruits.unshift('strawberries')
console.log(fruits);

/*
Output
--> ['strawberries','apples', 'bananas']
*/

🛑Notice: It is to be noticed that you can add multiple elements in the unshift() parameters.

// 👇 array
const fruits= ['oranges', 'apples', 'bananas']

// 👇 unshift() will add a new element 'strawberries' as the first elemtn and shift all the other elements to a higher index number
fruits.unshift('strawberries', 'peaches')
console.log(fruits);

/*
Output
--> ['strawberries','apples', 'bananas', 'peaches']
*/

BASIC6️⃣length

What if your father asks you how many fruits you have brought

// 👇 array
const fruits= ['oranges', 'apples', 'bananas']

// 👇 length will return the total number of elements in the array
console.log(fruits.length);

/*
Output
--> 3
*/

BASIC7️⃣Changing elements

Suppose your sweet young sister want you to carry peaches instead apples (which is a 2nd element) in your bag then how will you replace the 2nd element with peaches.

// 👇 array
const fruits= ['oranges', 'apples', 'bananas']

// 👇 Notice here, if I wanted to change 2nd element,
// I have to change element with index number 1
// ,because index numbers start from 0.
fruits[1] = 'peaches'
console.log(fruits);

/*
Output
--> [ 'oranges', 'peaches', 'bananas' ]
*/

🛑Notice: It is to be noticed that you can replace any element at any index number with this method. Just put the index number of the element.

BASIC8️⃣delete

we need to have an ability to delete an element in the array

// 👇 array
const fruits= ['oranges', 'apples', 'bananas']

// 👇 delete the element at the given index number
delete fruits[0]
console.log(fruits);

/*
Output
--> [ <1 empty item>, 'apples', 'bananas' ]
*/

🛑Notice: It is to be noticed that the other elements won’t change their index numbers which means that if we delete an element in between the arrays, the value at the index number of the element will be empty.

BASIC9️⃣concat()

What if you have two bags of fruits and you want to put fruits from one bag to another in JavaScript?

// 👇 array 1
const fruits1 = ['oranges', 'apples', 'bananas']
// 👇 array 2
const fruits2 = ['peaches', 'watermelon' , 'grapes']

// 👇 conact() will add elements of fruits 2 in fruits 1.
const bucket = fruits1.concat(fruits2)

console.log(bucket);

/*
Output
--> [ 'oranges', 'apples', 'bananas', 'peaches', 'watermelon', 'grapes' ]
*/
// 👇 array 1
const fruits1 = ['oranges', 'apples', 'bananas']
// 👇 array 2
const fruits2 = ['peaches', 'watermelon' , 'grapes']
// 👇 array 3
const fruits3 = ['muskmelon']

// 👇 conact() will add elements of fruits 2 and fruits 3 in fruits 1.
const bucket = fruits1.concat(fruits2, fruits3)

console.log(bucket);

/*
Output
--> [
  'oranges',
  'apples',
  'bananas',
  'peaches',
  'watermelon',
  'grapes',
  'muskmelon'
]
*/
// 👇 array
const fruits1 = ['oranges', 'apples', 'bananas']

// 👇 conact() will add 'peaches' in fruits 1.
const bucket = fruits1.concat('peaches')

console.log(bucket);

/*
Output
--> [ 'oranges', 'apples', 'bananas', 'peaches' ]
*/

Medium1️⃣splice()

With splice, you can add or remove any element in an array.

Parameters

  1. start number — The first parameter takes an index number at which you want to add or remove the elements.

  2. delete count — The second parameter takes a count of how many numbers should be deleted from the array at the start number(first parameter).

  3. items — The list of items that will be added after the deletion of elements (depending on deletion count) at the start number

👇 This is an example in which we will remove the bananas from the array.

// 👇 array
const fruits = ['oranges', 'apples', 'bananas']

// 👇 here, at index 2, which is bananas in our array, 1 (deletion count)
// element will be deleted.
fruits.splice(2, 1)

console.log(fruits);

/*
Output
--> [ 'oranges', 'apples' ]
*/

👇 This is an example in which we will remove the bananas as well as add peaches to the array

// 👇 array
const fruits = ['oranges', 'apples', 'bananas']

// 👇 here, at index 2, which is bananas in our array, 1 (deletion count)
// element will be deleted.
fruits.splice(2, 1, 'peaches')

console.log(fruits);

/*
Output
--> [ 'oranges', 'apples', 'peaches' ]
*/
// 👇 array
const fruits = ['oranges', 'apples', 'bananas']

// 👇 here, at index 2, which is bananas in our array, 1 (deletion count)
// element will be deleted.
// 👇 You can even add a list in the 3 parameter.
const newfruits = ['peaches', 'grapes']
fruits.splice(2, 1, newfruits)

console.log(fruits);

/*
Output
--> [ 'oranges', 'apples', 'peaches', 'grapes' ]
*/

Medium2️⃣slice()

Slice is used to make a new array that contains some of the elements from the given array.

Parameters

  1. Start — The first parameter will decide from which index number and elements should be selected for the new array.

  2. End — This is an optional parameter. This 2nd parameter will decide which index number and elements should be selected for the new array.

Notice that the start index number will also be included in the new array whereas the end index number will not be included in the new array.

// 👇 array
const fruits = ['oranges', 'apples', 'bananas']

// 👇 slice will select the elements from the index number 1.
// As we have not mentioned any end then it will select the elements till the end.
const last2elements = fruits.slice(1)

console.log(last2elements);

/*
Output
--> ['apples', 'bananas']
*/
// 👇 array
const fruits = ['oranges', 'apples', 'bananas', 'peaches', 'grapes']

// 👇 slice will select the elements from the index number 1 till 2 index number.
const elementsSelected = fruits.slice(1,4)

/*
Output
--> ['apples', 'bananas', 'peaches']
*/

Easy1️⃣sort()

What if you want to sort your fruits alphabetically?

// 👇 array
const fruits = ['oranges', 'apples', 'bananas', 'peaches', 'grapes']

fruits.sort()

console.log(fruits);

/*
Output
--> ['apples', 'bananas', 'peaches']
*/

Easy2️⃣reverse()

What if you want to reverse the order of your fruits?

// 👇 array
const fruits = ['oranges', 'apples', 'bananas', 'peaches', 'grapes']

fruits.reverse()

console.log(fruits);

/*
Output
--> [ 'grapes', 'peaches', 'bananas', 'apples', 'oranges' ]
*/

🥸Iterations

In arrays, if we want to go to every element and do some operation, then we can use iterations. It’s a loop in which, our function goes and performs some kind of operation.

1️⃣forEach()

With the help of forEach, we can perform a logic by going to each element of the array.

// 👇 array
const names = ['Dhruv', 'Harshil', 'Anurag', 'Mayank']

// foreach
names.forEach((value, index, array) => {
    console.log(index + ' -> ' + value);
    console.log(array)
})

/*
Output
--> 0 -> Dhruv
[ 'Dhruv', 'Harshil', 'Anurag', 'Mayank' ]
1 -> Harshil
[ 'Dhruv', 'Harshil', 'Anurag', 'Mayank' ]
2 -> Anurag
[ 'Dhruv', 'Harshil', 'Anurag', 'Mayank' ]
3 -> Mayank
[ 'Dhruv', 'Harshil', 'Anurag', 'Mayank' ]
*/

🥰Concept

What is happening behind forEach() is that the function goes to index number 0 and returns the value, then it goes to index number 1 and returns the value at that index, and so on.

ForEach() returns a callback function (it is a function that is passed into another function as an argument) which has the parameter as —

Value — The value at an index number.

Index — It is the index number of the value.

Array — It returns an array on which we are providing iteration.

2️⃣Map()

// 👇 array
const names = ['Dhruv', 'Harshil', 'Anurag', 'Mayank']

// map
names.map((value, index, array) => {
    console.log(index + ' -> ' + value);
    console.log(array)
})

/*
Output
--> 0 -> Dhruv
[ 'Dhruv', 'Harshil', 'Anurag', 'Mayank' ]
1 -> Harshil
[ 'Dhruv', 'Harshil', 'Anurag', 'Mayank' ]
2 -> Anurag
[ 'Dhruv', 'Harshil', 'Anurag', 'Mayank' ]
3 -> Mayank
[ 'Dhruv', 'Harshil', 'Anurag', 'Mayank' ]
*/

🥸Difference between map and forEach

map() is similar to forEach() but map() has the ability to return something. If you try to use return in forEach() , it won’t work.

// 👇 array
const names = ['Dhruv', 'Harshil', 'Anurag', 'Mayank']

// map
const nameMap = names.map((value, index, array) => {
    return index + '->' + value
})

console.log(nameMap);

/*
Output
--> 0 -> Dhruv
[ '0->Dhruv', '1->Harshil', '2->Anurag', '3->Mayank' ]
*/

3️⃣Reduce()

What if you created a list of numbers and you want that all the numbers in your list should be added and one single number should be returned?

Parameters

a. Callback function — It has the following parameters

  1. Previous number — It works as an accumulator.

  2. Current Value

  3. current Index

  4. array

b. Default value of the previous number — This is the value that you provide as the default value for the previous number.

 // 👇 array
const numbers = [1, 2, 10, 25]

// reduce
const sum = numbers.reduce((previousNumber, currentValue, currentIndex, array) => {
    console.log(previousNumber, currentValue)
    return previousNumber + currentValue;
}, 0) // 👈 0 is the default value

console.log('--');
console.log(sum);

/*
Output
--> 0 1
1 2
3 10
13 25
--
38
*/

🛑Notice: If you don’t provide a default value to the previous number, which in our case 0. Then the reduce function will take the first element of the array as the default value and will start looping through from 2nd element.

4️⃣IndexOf

What if your mother asks you to find the index number of fruit in your bag?

// 👇 array
const fruits = ["Apple", "Banana","Durian"];

// indexOf
const index = fruits.indexOf('Hi')
const index2 = fruits.indexOf('Apple')

console.log(index);
console.log(index2);

/*
Output
--> -1
0
*/

You can notice that if an element doesn’t exist in the array, then the function will return -1.

5️⃣find

Imagine your sister has designed a test in which every fruit will participate and only the fruit which passes the test will be returned.

// 👇 array
const fruits = ["Apple", "Banana","Durian", 'Apple'];

// find
const apple = fruits.find((value) => value === 'Apple')
const apple2 = fruits.find((value) => value === 'Appl')
console.log(apple);
console.log(apple2);

/*
Output
--> Apple
undefined
*/

You can see that if no element passes the test, then undefined is returned.

6️⃣Filter

As we saw how find just returns a single element, what if you want a test in which those elements should be removed from the array which passes the test?

// 👇 array
const fruits = ["Apple", "Banana","Durian", 'Apple'];

// filter 
const fruitsWithA = fruits.filter((value ) => value.startsWith('A'))
// 👆 startsWith checks the first letter of the string.

console.log(fruitsWithA);

/*
Output
--> [ 'Apple', 'Apple' ]
*/

7️⃣includes

What if you have bought so many fruits and your father asks you if you have brought an apple for him? How will you check that

// 👇 array
const fruits = ["Apple", "Banana","Durian", 'Apple'];

// includes
const apple = fruits.includes('Apple')
const grapes = fruits.includes('grapes')

console.log(apple);
console.log(grapes);

/*
Output
--> true
false
*/

via GIPHY

Thanks for reading this blog.

Did you find this article valuable?

Support Next Dev by becoming a sponsor. Any amount is appreciated!