In this tutorial, we are going to practice Arrays in JavaScript. Before doing these examples you should have a good understanding of Arrays in JavaScript.
Example 1: Javascript program to find any number in an array.
const arr = [6,3,"Pixelcodepro", "coding", 8]
var num = 3;
for(var i = 0;i<arr.length;i++)
{
if(arr[i]==num)
{
console.log("The number "+num+" is present in the array");
break;
}
}
The output of the code is
The number 3 is present in the array
Example 2: Javascript program to add all the numbers in an array.
const arr = [6,3,8,9,2]
var sum = 0;
for(var i = 0;i<arr.length;i++)
{
sum = sum + arr[i];
}
console.log("The sum of numbers in array is "+sum);
The output of the code is
The sum of numbers in array is 28
Example 3: Javascript program to swap the first and last elements in an array.
const arr = [6,3,8,9,2]
let temp;
let n = arr.length-1;
temp = arr[0];
arr[0]=arr[n];
arr[n]=temp;
console.log(arr);
The output of the code is
[2,3,8,9,6]
Example 4: Javascript program to concat two arrays.
const arr1 = [6,3,8,9,2]
const arr2 = [4,3];
const arr3 = ["coding","Javascript"];
// to concat two arrays
const arr4 = arr1.concat(arr2);
console.log(arr4);
//to concat three arrays
const arr5 = arr1.concat(arr2,arr3);
console.log(arr5);
The output of the code is
[6,3,8,9,2,4,3]
[6,3,8,9,2,4,3,"coding","Javascript"]
Example 5: Javascript program to find the number of times a specific element is present in an array.
var arr = [4,3,2,5,4,6,7,4,11,23,4,55]
var count = 0;
var number = 4;
for(var i = 0;i<arr.length;i++)
{
if(arr[i] == 4)
{
count = count + 1;
}
}
console.log(`The number ${number} is present ${count} times`);
The output of the code is
The number 4 is present 4 times
Example 6: Javascript program to find the average of all numbers in an array.
const arr = [6,3,8,9,2,44,32,22]
var sum = 0;
for(var i = 0;i<arr.length;i++)
{
sum = sum + arr[i];
}
var avg = sum/arr.length;
console.log("The average of all the numbers in an array is "+avg);
The output of the code is
The average of all the numbers in an array is 15.75
Example 7: Javascript program to find the Max and Min in an array.
const arr = [6,3,8,9,2,44,32,220]
var min = arr[0],max=arr[0];
for(var i = 0;i<arr.length;i++)
{
if(min>arr[i])
{
min = arr[i];
}
if(max<arr[i])
{
max = arr[i];
}
}
console.log("Max = "+max+"\nMin = "+min);
The output of the code is
Max = 220
Min = 2
Example 8: Javascript program to sort an array using sort() function.
const arr = [6,3,8,9,2,44,32,220]
var min = arr[0],max=arr[0];
arr.sort(function(a,b){return a-b})
console.log(arr)
The output of the code is
[2,3,6,8,9,32,44,220]