Exercise on JS Array

Exercise on JS Array

// No 1
const Input = [1, 2, 4, 0];
const input2 = ( 'w3resource');
console.log (Array.isArray (Input));
console.log (Array.isArray(input2));


//No 2
function cloneArray(array) {
    return array.slice(0);
}
  const orignalArray = [1, 2, [4, 0]];
  const clonedArray = cloneArray(orignalArray);
  console.log(orignalArray); 
  console.log(clonedArray);


//No 3
function first(arr, n = 1) {
  if (n >= 0) {
    return arr.slice(0, n);
  } else {
    return [];
  }
}
// Example usage:
console.log(first([7, 9, 0, -2]));       
console.log(first([], 3));              
console.log(first([7, 9, 0, -2], 3));      
console.log(first([7, 9, 0, -2], 6));       
console.log(first([7, 9, 0, -2], -3));  



// No 4
function getLastElements(arr, n) {
    if (n=== undefined) {
        return arr [arr.lenght -1];
    } else { return arr.slice ( -n);}
  }
    console.log(getLastElements ([7, 9, 0, -2]));
console.log( getLastElements([],3));
console.log( getLastElements ([7, 9, 0, -2],3));
console.log( getLastElements([7, 9, 0, -2],6));
console.log( getLastElements([7, 9, 0, -2],-3));


// No 5
const myColor = ["Red", "Green", "White", "Black"];
const commaSeparated = myColor.join(",");
console.log(commaSeparated); 


// NO 6
function insertDashes(number) {
    var numberString = number.toString();
    var result = '';
    for (var i = 0; i < numberString.length; i++) {
      result += numberString[i];
      if (numberString[i] % 2 === 0 && numberString[i + 1] % 2 === 0) {
        result += '-';
      }
    }
    return result;
  }
//   // Example usage
  var input = 025468;
  var output = insertDashes(input);
  console.log(output); // Output: 0-254-6-8


// NO 7
var arr1 = [-3, 8, 7, 6, 5, -4, 3, 2, 1];
arr1.sort(function(a, b) {
  return a - b;
});
console.log(arr1.join(','));


// No 8
function findMostFrequentItem(arr) {
  let frequency = {};
  let maxCount = 0;
  let mostFrequentItem;
  // Count the occurrences of each item in the array
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i];
    frequency[item] = (frequency[item] || 0) + 1;
    if (frequency[item] > maxCount) {
      maxCount = frequency[item];
      mostFrequentItem = item;
    }
  }
  return `${mostFrequentItem} (${maxCount} times)`;
}
// Example usage:
const arr10 = [3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3];
const result12 = findMostFrequentItem(arr10);
console.log(result12); 


// No 9
function swapCase(str) {
    var swappedStr = '';
    for (var i = 0; i < str.length; i++) {
      var char = str.charAt(i);
      if (char === char.toLowerCase()) {
        swappedStr += char.toUpperCase();
      } else {
        swappedStr += char.toLowerCase();
      }
    }
    return swappedStr;
  }
  var input = 'The Quick Brown Fox';
  var output = swapCase(input);
  console.log(output);


// No 10
var a = [[1, 2, 1, 24], [8, 11, 9, 4], [7, 0, 7, 27], [7, 4, 28, 14], [3, 10, 26, 7]];
for (var i = 0; i < a.length; i++) {
  for (var j = 0; j < a[i].length; j++) {
    console.log(a[i][j]);
  }
}


// No 11
function sumOfSquares(vector) {
    let sum = 0;
    for (let i = 0; i < vector.length; i++) {
      sum += vector[i] * vector[i];
    }
    return sum;
  }
  // Example usage
  const numericalVector = [2, 3, 4, 5];
  const rsult = sumOfSquares(numericalVector);
  console.log(rsult);


// No 12
function computeSumAndProduct(array) {
    let sum = 0;
    let product = 1;
    for (let i = 0; i < array.length; i++) {
      sum += array[i];
      product *= array[i];
    }
    return { sum, product };
  }
  // Example usage
  const integers = [2, 4, 6, 8];
  const result = computeSumAndProduct(integers);
  console.log("Sum:", result.sum);
  console.log("Product:", result.product);


// No 13
function addNewItem() {
    let arrayMsg = [];
    arrayMsg = [...arrayMsg, 'hello world!'];
    arrayMsg = [...arrayMsg, 'im from nigeria!']
    console.log(arrayMsg.join(', '))
}
addNewItem();


// No 14
function removeDuplicates(array) {
    const uniqueArray = [];
    for (let i = 0; i < array.length; i++) {
      const currentItem = array[i].toLowerCase();
      if (!uniqueArray.includes(currentItem)) {
        uniqueArray.push(currentItem);
      }
    }
    return uniqueArray;
  }
  // Example usage
  const items = ["Apple", "banana", "apple", "Orange", "banana"];
  const uniqueItems = removeDuplicates(items);
  console.log(uniqueItems);


// No 15
let color = ["Blue ", "Green", "Red", "Orange", "Violet", "Indigo", "Yellow "];
console.log( 1 + ' 1st Choice is ' + color[0])
console.log( 2 + ' 2nd Choice is ' + color[1])
console.log( 3 + ' 3rd Choice is ' + color[0])


// No 16
function findLeapYears(startYear, endYear) {
    const leapYears = [];
    for (let year = startYear; year <= endYear; year++) {
      if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
        leapYears.push(year);
      }
    }
    return leapYears;
  }
  // Example usage
  const startYear = 2000;
  const endYear = 2020;
  const leapYears = findLeapYears(startYear, endYear);
  console.log(leapYears);


  // No 17
  function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
  }
  // Example usage
  const originalArray = [1, 2, 3, 4, 5];
  const shuffledArray = shuffleArray(originalArray);
  console.log(shuffledArray);


  // No 18
function binary_Search(array, target) {
  let low = 0;
  let high = array.length - 1;
  while (low <= high) {
    const mid = Math.floor((low + high) / 2);
    if (array[mid] === target) {
      return mid; // Found the target at index mid
    } else if (array[mid] < target) {
      low = mid + 1; // Target is in the right half
    } else {
      high = mid - 1; // Target is in the left half
    }
  }
  return -1; // Target not found
}
// Example usage
const tems = [1, 2, 3, 4, 5, 7, 8, 9];
const target = 5;
const index = binary_Search(tems, target);
console.log(binary_Search, 0);
console.log(binary_Search, 5);


// No 19
function computeSum(array1, array2) {
  const result = [];
  const maxLength = Math.max(array1.length, array2.length);
  for (let i = 0; i < maxLength; i++) {
    const value1 = array1[i] || 0;
    const value2 = array2[i] || 0;
    result.push(value1 + value2);
  }
  return result;
}
// Example usage
const array1 = [1, 0, 2, 3, 4];
const array2 = [3, 5, 6, 7, 8, 13];
const sumArray = computeSum(array1, array2);
console.log(sumArray);



// No 20
function findDuplicates(array) {
  const duplicates = [];
  const visited = {};
  for (let i = 0; i < array.length; i++) {
    const element = array[i];

    if (visited[element]) {
      if (!duplicates.includes(element)) {
        duplicates.push(element);
      }
    } else {
      visited[element] = true;
    }
  }
  return duplicates;
}
// Example usage
const array = [1, 2, 3, 4, 5, 2, 7, 3, 5];
const duplicateValues = findDuplicates(array);