Skip to content

Latest commit

 

History

History
157 lines (109 loc) · 2.63 KB

20-07-23.md

File metadata and controls

157 lines (109 loc) · 2.63 KB

Array Practice

Write a program to add the values of an array

let arr = [1, 2, 3, 4, 5];
arr.push(34);

console.log(arr);
// [1, 2, 3, 4, 5, 34]

​Write a program to calculate the average value of array

let arr = [1, 2, 3, 4, 5];
let totalSum = arr.reduce((num, sum) => sum += num, 0);
let arrLength = arr.length;
let avgValue = totalSum / arrLenght;

console.log(avgVal);
// 3

Write a program to remove a particular element from an array

let arr = [1, 2, 3, 4, 5];

let valueToBeRemoved = 4;
arr = arr.filter(num => num !== valueToBeRemoved);

console.log(arr);
// [1, 2, 3, 5]

​Write a program to reverse an array

let arr = [1, 2, 3, 4, 5];

let newArray = [];
for(let num of arr) {
    newArray.unshift(i);
}

console.log(newArray);
// [5, 4, 3, 2, 1]

Write a program to get highest value from array

let arr = [1, 2, 3, 4, 5];

let high = arr[0];

for(let num of arr) {
    high = (high < num) ? num : high;
}

console.log(high);
// 5

​Write a program to get the lowest value from array

let arr = [1, 2, 3, 4, 5];

let low = arr[0];

for(let num of arr) {
    low = (low < num) ? low : num;
}

console.log(low);

Write a program to get second highest value from array

let arr = [1, 2, 3, 4, 5];

function high(arr) {
    let high = arr[0];

    for(let num of arr) {
        high = (high > num) ? high : num;
    }

    return high;
}

let valueToBeRemoved = high(arr);
arr = arr.filter(num => num !== valueToBeRemoved);

console.log(high(arr));
// 4

​Write a program to get second lowest value from array

let arr = [1, 2, 3, 4, 5];

function low(arr) {
    let low = arr[0];

    for(let num of arr) {
        low = (low < num) ? low : num;
    }

    return low;
}

let valueToBeRemoved = low(arr);
arr = arr.filter(num => num !== valueToBeRemoved);

console.log(low(arr));
// 2

​Write a program to copy the elements from one array to another array

let arr = [4, 34, "fgs3", "gasg", "546t", 345];

let copiedArr = [ ...arr ];

console.log(copiedArr);
// [4, 34, "fgs3", "gasg", "546t", 345]

Write a program to create a One D Array and insert Random Numbers

let arr = [ 4, 34, 345 ];

let insertFirst = Math.floor(Math.random() * 1000);
let insertLast = Math.floor(Math.random() * 1000);
let insertAtIndex = Math.floor(Math.random() * 1000);

arr.unshift(insertFirst);
arr.push(insertLast);

let insertIndex = Math.floor(Math.random() * arr.length);
arr = [...arr.slice(0, insertIndex), insertAtIndex, ...arr.slice(insertIndex)]

console.log({
    insertFirst, 
    insertLast, 
    insertAtIndex, 
    insertIndex, 
    arr
});