By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
rocoderesrocoderes
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Notification Show More
Latest News
How to set the dropdown value by clicking on a table row
Javascript – How to set the dropdown value by clicking on a table row
JavaScript
Attempting to increase the counter, when the object's tag exist
Javascript – Attempting to increase the counter, when the object’s tag exist
JavaScript
Cycle2 JS center active slide
Javascript – Cycle2 JS center active slide
JavaScript
Can import all THREE.js post processing modules as ES6 modules except OutputPass
Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass
JavaScript
How to return closest match for an array in Google Sheets Appscript
Javascript – How to return closest match for an array in Google Sheets Appscript
JavaScript
Aa
Aa
rocoderesrocoderes
Search
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Follow US
High Quality Design Resources for Free.
rocoderes > JavaScript > Arrays in JavaScript
JavaScript

Arrays in JavaScript

Rohan750
Last updated: 2021/05/16 at 5:38 AM
Rohan750
Share
11 Min Read

Contents
1.Traversal in arrayfor infor ofArray.forEach()2)Searching and Filter in an Array1)Array.indexOf()2)Array.lastIndexOf()3)Array.includes()4)Array.find()5)Array.findIndex()6)Array.filter()3)Perform CRUD operation in Array1)Array.push()2)Array.unshift()3)Array.pop()4)Array.shift() challenge Time 5)Array.splice()4)Map and Reduce Method 1)Array.map()2)Reduce Method watch the video:https://youtu.be/KGkiIBTq0y0

Arrays in javascript

In JavaScript, arrays are used to store multiple values in a single variable. When we use var, we can store only one value at a time. but we use an array then we can store multiple values in a single variable.

Example:


var myFriends = ['jay',"brock","male",false,20,"male",'vishal',true, 52];

console.log(myFriends);

1.Traversal in array

if we want to get the single data at a time and also if we want to change the data.

Example:


var myFriends = ['rohan','rahul','beast','vishal'];

console.log(myFriends[myFriends.length - 1]);

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js
vishal

PS C:UsersThe-BeastDesktopjavascript Blog>

if we want to check the length of elements of an array


var myFriends = ['rohan','rahul','beast','vishal'];

console.log(myFriends.length);

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js
4

PS C:UsersThe-BeastDesktopjavascript Blog> 

we use for loop to navigate


var myFriends = ['rohan','rahul','beast','vishal'];
for(var i=0; i < myFriends.length; i++){
  console.log(myFriends[i]);
}

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js
rohan 
rahul 
beast 
vishal
PS C:UsersThe-BeastDesktopjavascript Blog> 

After ES6 we have for..in and for..of loop too

for in

for in loops through the properties of an object(means print only index value)

Example:


var myFriends = ['rohan','rahul','beast','vishal'];

for(let element in myFriends){
        console.log(element)
}

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js
0
1
2
3
PS C:UsersThe-BeastDesktopjavascript Blog> 

for of

for of loops through the values of an iterable object(print array element).

Example 


var myFriends = ['rohan', 'rahul', 'beast', 'vishal'];
for (let element of myFriends) {
        console.log(element)
}

output


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js
rohan
rahul 
beast 
vishal
PS C:UsersThe-BeastDesktopjavascript Blog> 

Array.forEach()

Calls a function for each element in the array.

Note:forEach() reaturn a undefined

 the function takes 3 arguments:

1)array element

2)element index

3)array itself

Example:


var myFriends = ['rohan', 'rahul', 'beast', 'vishal'];


myFriends.forEach(function (element, index, array) {

        console.log(element + " index : " + index + " " + array)

})

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js
rohan index : 0 rohan,rahul,beast,vishal
rahul index : 1 rohan,rahul,beast,vishal
beast index : 2 rohan,rahul,beast,vishal
vishal index : 3 rohan,rahul,beast,vishal
PS C:UsersThe-BeastDesktopjavascript Blog> 

2)Searching and Filter in an Array

1)Array.indexOf()

Returns the first index of an element within the array equal to an element, or -1 if none is found. It search the element from the 0th index number.

Example:


var myFriends = ['rohan', 'rahul', 'beast', 'vishal', "beast"];

console.log(myFriends.indexOf("beast"))
console.log(myFriends.indexOf("beast", 3))

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js
2
4
PS C:UsersThe-BeastDesktopjavascript Blog> 

2)Array.lastIndexOf()

Returns the last index of an element within the array equal to an element, or -1 if none is found. It search the element last to first.

Example:


var myFriends = ['rohan', 'rahul', 'beast', 'vishal', "beast"];

console.log(myFriends.lastIndexOf("beast"))
console.log(myFriends.lastIndexOf("beast", 3))

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js
4
2
PS C:UsersThe-BeastDesktopjavascript Blog> 

here indexOf() is Forward and lastIndexOf() is Backward

3)Array.includes()

Determines whether the array contains a value, returning true or false as appropriate.

Example:


var myFriends = ['rohan', 'rahul', 'beast', 'vishal', "beast"];


console.log(myFriends.includes("rohan"))
console.log(myFriends.includes("Rohan"))

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js
true 
false
PS C:UsersThe-BeastDesktopjavascript Blog> 

4)Array.find()

–>array.find(function(element, index, array),thisValue)
–>Returns the found element in the array, if some element in the array satisfies the testing function, or undefined if not found.
–>The only problem is that it return only one element.

Example:


const prices = [200, 300, 350, 400, 450, 500, 600];
const findElem = prices.find((element, index, array) => {
        return element < 400

})
console.log(findElem)

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js
200
PS C:UsersThe-BeastDesktopjavascript Blog> 

5)Array.findIndex()

Returns the found index in the array, if an element in the array satisfies the testing function, or -1 if not found.

Example:


const prices = [200, 300, 350, 400, 450, 500, 600];
const findElem = prices.findIndex((currEle) => {
        return currEle > 500
})
console.log(findElem)

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js
6
PS C:UsersThe-BeastDesktopjavascript Blog> 

6)Array.filter()

Returns a new array containing all elements of the calling array for which the provided filtering function returns true.

Example:


const prices = [200, 300, 350, 400, 450, 500, 600];
const priceTag = prices.filter((CurrVal, index, array) => {
        return CurrVal < 400
})
console.log(priceTag)

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js
[ 200, 300, 350 ]
PS C:UsersThe-BeastDesktopjavascript Blog> 

3)Perform CRUD operation in Array

1)Array.push()

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

Example:


const animals = ['pigs', 'goats', 'sheep'];

const count = animals.push('chicken');
console.log(count);

animals.push('chicken', 'cats', 'cow');
console.log(animals);

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js
4       
[
  'pigs',    'goats',  
  'sheep',   'chicken',
  'chicken', 'cats',   
  'cow'
]
PS C:UsersThe-BeastDesktopjavascript Blog> 

2)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:


const animals = ['pigs', 'goats', 'sheep'];

const count = animals.unshift('chicken');
console.log(count);
console.log(animals);

animals.unshift('chicken', 'cats', 'cow');
console.log(animals);

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js
4
[ 'chicken', 'pigs', 'goats', 'sheep' ]
[
  'chicken', 'cats',   
  'cow',     'chicken',
  'pigs',    'goats',  
  'sheep'
]
PS C:UsersThe-BeastDesktopjavascript Blog> 

3)Array.pop()

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

Example:


const plants = ['broccoli', 'cauliflower', 'kale', 'tomato', 'cabbage'];

console.log(plants);
console.log(plants.pop());
console.log(plants);

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js
[ 'broccoli', 'cauliflower', 'kale', 'tomato', 'cabbage' ]
cabbage
[ 'broccoli', 'cauliflower', 'kale', 'tomato' ]
PS C:UsersThe-BeastDesktopjavascript Blog> 

4)Array.shift()

The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.

Example:



const plants = ['broccoli', 'cauliflower', 'kale', 'tomato', 'cabbage'];
console.log(plants);
console.log(plants.shift());
console.log(plants);

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js
[ 'broccoli', 'cauliflower', 'kale', 'tomato', 'cabbage' ]
broccoli
[ 'cauliflower', 'kale', 'tomato', 'cabbage' ]
PS C:UsersThe-BeastDesktopjavascript Blog> 

challenge Time

5)Array.splice()

Adds and/or removes elements from an array.
Note: This method changes the original array.
syntax: Array.splice(index, howmany, item1, ….., itemX)

1: Add Dec at the end of an array?

2: What is the return value of the splice method?

3: update march to March (update)?

4: Delete June from an array?

solution 1:


const months = ['Jan', 'march', 'April', 'June', 'July'];
const newMonth = months.splice(months.length, 0, "Dec");
console.log(months);

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js
[ 'Jan', 'march', 'April', 'June', 'July', 'Dec' ]

PS C:UsersThe-BeastDesktopjavascript Blog> 

solution 2:

return A new Array, containing the removed items( if any)


const months = ['Jan', 'march', 'April', 'June', 'July'];
const newMonth = months.splice(months.length, 0, "Dec");
console.log(months);
console.log(newMonth);

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js
[ 'Jan', 'march', 'April', 'June', 'July', 'Dec' ]
[]
PS C:UsersThe-BeastDesktopjavascript Blog> 

solution 3:


const months = ['Jan', 'march', 'April', 'June', 'July'];

const indexOfMonth = months.indexOf('march');

if (indexOfMonth != -1) {
        const updateMonth = months.splice(indexOfMonth, 1, "March");
        console.log(months);
        console.log(updateMonth);
} else {
        console.log('No such data found');
}

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js
[ 'Jan', 'March', 'April', 'June', 'July' ]
[ 'march' ]
PS C:UsersThe-BeastDesktopjavascript Blog> 

solution 4:



const indexOfMonth = months.indexOf('June');

if (indexOfMonth != -1) {
        const updateMonth = months.splice(indexOfMonth, 1);
        console.log(months);
} else {
        console.log('No such data found');
}

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js
[ 'Jan', 'march', 'April', 'July' ]

PS C:UsersThe-BeastDesktopjavascript Blog>

4)Map and Reduce Method

 1)Array.map()

 Returns a new array containing the results of calling a function on every element in this array. 
 Note: this method does not change the original array.
syntax: Array.map(function (currentValue, index, arr), thisValue)

Example 1:


const array1 = [1, 4, 9, 16, 25];

let newArr = array1.map((curElem, index, arr) => {
        return curElem > 9;
})
console.log(array1);
console.log(newArr);

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js
[ 1, 4, 9, 16, 25 ]
[ false, false, false, true, true ]
PS C:UsersThe-BeastDesktopjavascript Blog> 

Example 2:


const array1 = [1, 4, 9, 16, 25];
let newArr = array1.map((curElm, index, arr) => {
        return `Index no = ${index} and the value is ${curElm} belong to ${arr} `
})
console.log(newArr);

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js
[
  'Index no = 0 and the value is 1 belong to 1,4,9,16,25 ', 
  'Index no = 1 and the value is 4 belong to 1,4,9,16,25 ', 
  'Index no = 2 and the value is 9 belong to 1,4,9,16,25 ', 
  'Index no = 3 and the value is 16 belong to 1,4,9,16,25 ',
  'Index no = 4 and the value is 25 belong to 1,4,9,16,25 ' 
]
PS C:UsersThe-BeastDesktopjavascript Blog> 

2)Reduce Method

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

The reducer function takes four arguments:
1. Accumulator
2. Current Value
3. Current Index
4. Source Array

Example:


let arr = [5, 6, 2];

let sum = arr.reduce((accumulator, curElem) => {
        return accumulator += curElem;
})
console.log(sum)

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js
13

PS C:UsersThe-BeastDesktopjavascript Blog>

watch the video:https://youtu.be/KGkiIBTq0y0

Related

Subscribe to Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Share this Article
Facebook Twitter Email Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Previous Article Modern JavaScript
Next Article Strings in javascript
4 Comments 4 Comments
  • Lilly says:
    November 16, 2021 at 7:48 pm

    I am regular reader, how are you everybody? This piece of writing
    posted at this site is truly pleasant.

    Reply
  • Leonie says:
    November 19, 2021 at 12:21 am

    I couldn’t resist commenting. Well written!

    Reply
  • Hallie says:
    November 21, 2021 at 2:56 pm

    Good day I am so delighted I found your blog, I really found
    you by error, while I was looking on Askjeeve for something else, Anyways I am here now and would just like to say cheers for a tremendous post and
    a all round entertaining blog (I also love the theme/design), I don’t have time
    to browse it all at the minute but I have bookmarked it and also added in your RSS feeds, so
    when I have time I will be back to read a lot more, Please
    do keep up the awesome jo.

    Reply
  • houston junk car buyer says:
    May 5, 2022 at 8:17 am

    Hello to every body, it’s my first pay a quick visit of
    this webpage; this weblog contains remarkable and
    genuinely good information for readers.

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

- Advertisement -

You Might Also Like

How to set the dropdown value by clicking on a table row

Javascript – How to set the dropdown value by clicking on a table row

February 11, 2024
Attempting to increase the counter, when the object's tag exist

Javascript – Attempting to increase the counter, when the object’s tag exist

February 11, 2024
Cycle2 JS center active slide

Javascript – Cycle2 JS center active slide

February 10, 2024
Can import all THREE.js post processing modules as ES6 modules except OutputPass

Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass

February 10, 2024
rocoderesrocoderes
Follow US

Copyright © 2022 All Right Reserved By Rocoderes

  • Home
  • About us
  • Contact us
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc.

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?