0% found this document useful (0 votes)
125 views13 pages

JavaScript Array Functions Guide

Uploaded by

divyaas340
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
125 views13 pages

JavaScript Array Functions Guide

Uploaded by

divyaas340
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Array Exercise

[Link] a function that creates an array of numbers from 1 to


`n`.

function createArray(n) {

const arr = [];

for (let i = 1; i <= n; i++) {

[Link](i); // You can replace this with manual indexing

return arr;

[Link](createArray(5))

2. Write a function to find the largest number in an array.

function findMax(arr) {

let max = arr[0];

for (let i = 1; i < [Link]; i++) {

if (arr[i] > max) {


max = arr[i];

return max;

[Link](findMax([1,2,6,4,90]))

[Link] a function to find the smallest number in an array.

function findMin(arr) {

let min = arr[0];

for (let i = 1; i < [Link]; i++) {

if (arr[i] < min) {

min = arr[i];

return min;

[Link](findMin([3,2,1,7,4]))
4. Write a function to calculate the sum of all elements in an
array.

function sumArray(arr) {

let sum = 0;

for (let i = 0; i < [Link]; i++) {

sum += arr[i];

return sum;

[Link](sumArray([1,2,3,4,5,6]))

[Link] a function to calculate the average value of an array.

function averageArray(arr) {

let sum = sumArray(arr);

return sum / [Link];

[Link](averageArray([1,2,3,4,5]))
6. Write a function that counts the number of even and odd
numbers in an array.

function countEvenOdd(arr) {

let evenCount = 0;

let oddCount = 0;

for (let i = 0; i < [Link]; i++) {

if (arr[i] % 2 === 0) {

evenCount++;

} else {

oddCount++;

return { evenCount, oddCount };

[Link](countEvenOdd(1,2,3,4,5,6,7,8))
7. Write a function to reverse the elements of an array.

function reverseArray(arr) {

const reversed = [];

for (let i = [Link] - 1; i >= 0; i--) {

[Link](arr[i]);

return reversed;

[Link](reverseArray([1,2,3,4,5]))

[Link] a function that removes duplicates from an array.

function removeDuplicates(arr) {

const unique = [];

for (let i = 0; i < [Link]; i++) {

if (![Link](arr[i])) {

[Link](arr[i]);

}
return unique;

[Link](removeDuplicates(1,1,2,3,5,4,7,3,2,5))

9. Write a function that checks if a specific element exists in an


array.

function containsElement(arr, element) {

for (let i = 0; i < [Link]; i++) {

if (arr[i] === element) {

return true;

return false;

[Link](containsElement([1,2,3,4,5,6],6))

[Link] a function that sorts an array without using built-in


sort methods.
function bubbleSort(arr) {

for (let i = 0; i < [Link]; i++) {

for (let j = 0; j < [Link] - i - 1; j++) {

if (arr[j] > arr[j + 1]) {

// Swap

const temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

return arr;

[Link](bubbleSort([3,4,6,7,1,2]))

[Link] a function that counts the elements in an array


without using the `length` property.
function countElements(arr) {

let count = 0;

for (let i = 0; arr[i] !== undefined; i++) {

count++;

return count;

[Link](countElements([1,2,3,4,5,6,7,8,9]))

12. Write a function that merges two arrays into one.

function mergeArrays(arr1, arr2) {

const merged = [];

for (let i = 0; i < [Link]; i++) {

[Link](arr1[i]);

for (let j = 0; j < [Link]; j++) {

[Link](arr2[j]);

return merged;
}

[Link](mergedArrays([1,2,3,4],[5,6,7,8]))

13. Write a function that returns the index of a specific


element in an array.

function findIndex(arr, element) {

for (let i = 0; i < [Link]; i++) {

if (arr[i] === element) {

return i;

return -1; // Element not found

[Link](findIndex([1,2,3,4],4))

[Link] a function that shifts all elements in an array to the


left.
function shiftLeft(arr) {

const shifted = [];

for (let i = 1; i < [Link]; i++) {

[Link](arr[i]);

return shifted;

[Link](shiftLeft([1,2,3,4]))

15. Write a function that removes the last element of an array


without using pop.

function removeLast(arr) {

const newArr = [];

for (let i = 0; i < [Link] - 1; i++) {

[Link](arr[i]);

return newArr;

[Link](removeLast([1,2,3,4]))
[Link] a function that retrieves the last element of an array.

function getLastElement(arr) {

return arr[[Link] - 1];

[Link](getLastElement([1,2,3,4,5]))

17. Write a function that retrieves the first element of an


array.

function getFirstElement(arr) {

return arr[0];

[Link](getFirstElement([1,2,3,4]))

[Link] a function that repeats an array a specified number


of times.
function repeatArray(arr, times) {

const result = [];

for (let t = 0; t < times; t++) {

for (let i = 0; i < [Link]; i++) {

[Link](arr[i]);

return result;

[Link](repeatArray([1,2,3,4],3))

19. Write a function that extracts a portion of an array


between two indices.

function extractSubarray(arr, start, end) {

const subarray = [];

for (let i = start; i < end && i < [Link]; i++) {

[Link](arr[i]);

return subarray;
}

[Link](extractSubarray([1,2,3,4,5],2,4))

Common questions

Powered by AI

The 'countElements' function operates by iterating over the array until it encounters an undefined value, which signals the end of the array, incrementing a count on each iteration . This reveals a fundamental aspect of array manipulation in JavaScript, showcasing an understanding of array boundaries through iterative checks rather than relying on predefined properties like 'length'. This technique, while less efficient than directly using 'length', illustrates a manual approach to traversal and highlights JavaScript's flexible handling of array-like structures.

The 'removeLast' function, implemented without using 'pop', affects time complexity since it involves creating a new array and copying all elements except the last, contrasting with the O(1) time complexity of using 'pop' . This approach results in an O(n) time complexity due to looping over n - 1 elements. An advantage is manual control over the array contents, useful for environments or languages without built-in array methods. A disadvantage is inefficiency for large datasets, where it's less performant than direct method calls.

'mergeArrays' demonstrates concatenation by sequentially looping through two arrays and appending their elements to a new combined array . This approach showcases array union through straightforward append operations, independent of the initial array sizes; it handles arrays of differing lengths by maintaining separate loops for each. This guarantees all elements from both arrays are included in the merged result, reflecting a basic but effective method for array concatenation in programming.

'removeDuplicates' and 'containsElement' serve different purposes: 'removeDuplicates' iterates over an array to create a new array containing only unique elements, effectively removing any duplicate values . 'containsElement', on the other hand, checks if a specified element exists in the array by iterating through it until a match is found, returning a boolean value . While 'removeDuplicates' modifies the array to ensure uniqueness, 'containsElement' simply verifies the presence of an element without altering the array.

'extractSubarray' handles index boundaries by ensuring the loop iterates from the starting index 'start' to the ending index 'end', checking that it doesn't exceed the array's length . It effectively constructs a subarray from specified indices without causing out-of-bounds errors, given valid indices. However, if indices provided are invalid (negative or exceeding array length), the function could produce unexpected results or errors, highlighting the necessity for input validation to prevent edge-case failures.

The 'bubbleSort' method sorts an array by repeatedly swapping adjacent elements if they are in the wrong order, resulting in a time complexity of O(n^2) due to the nested loops iterating over the array . This is significantly less efficient than native sorting functions like JavaScript's Array.prototype.sort(), which employs a time complexity often around O(n log n) using adaptive algorithms like Timsort or QuickSort. Native functions are generally faster and more optimized for practical use cases, making them better suited for large datasets.

The 'shiftLeft' function alters an array by starting from the second element and appending each subsequent element to a new array . This effectively removes the first element and shifts the rest to the left. The technique preserves data integrity for elements after the first index but discards the first element entirely. Every element's index is reduced by one relative to the original array, reflecting a typical shiftLeft operation where data preservation concerns are isolated to elements beyond the initial position.

To create an array of numbers from 1 to n, you can use a function such as createArray. This function initializes an empty array and appends numbers incrementally from 1 to n using a loop . The implications for algorithm efficiency involve a time complexity of O(n) since the function iterates n times, and a space complexity of O(n) as the array stores n elements. This approach is efficient for generating consecutive integers up to a moderate size but can face performance issues for very large n due to memory limitations and processing time.

The relationship between 'sumArray' and 'averageArray' demonstrates a direct dependency, where 'averageArray' uses the total produced by 'sumArray' to compute the average by dividing the sum by the number of elements in the array . The accuracy of 'averageArray' hinges on 'sumArray' correctly summing all elements, exemplifying a composite operation where the higher-level calculation depends on the integrity of foundational procedures.

The 'findMax' function identifies the largest number in an array by initializing a variable 'max' to the first array element, then iterating through the array, updating 'max' whenever it encounters a larger element . This ensures accuracy by systematically comparing each element, assuming the initial value is accurate, and updates only when a larger value is found, thus it comprehensively examines the whole array.

You might also like