W3Resource JavaScript array – Exercises, Practice, Solution

Home   »   W3Resource JavaScript array – Exercises, Practice, Solution

// 1. Write a JavaScript function to check whether an `input` is an array or not. Go to the editor
// Test Data :
// console.log(is_array('w3resource'));
// console.log(is_array([1, 2, 4, 0]));
// false
// true

// Solution
(function () {
  const isArray = (arr) => {
    return toString.call(arr) === "[object Array]";
  };
})();

/****************************************************************************************************************************/

// 2. Write a JavaScript function to clone an array. Go to the editor
// Test Data :
// console.log(array_Clone([1, 2, 4, 0]));
// console.log(array_Clone([1, 2, [4, 0]]));
// [1, 2, 4, 0]
// [1, 2, [4, 0]]

// Solution
(function () {
  const testArray = [1, 2, [4, 0]];

  const cloneArr = (arr) => {
    return arr.map((item) => {
      if (Array.isArray(item)) {
        return cloneArr(item);
      } else {
        return item;
      }
    });
  };
})();

/****************************************************************************************************************************/

// 3. Write a JavaScript function to get the first element of an array. Passing a parameter 'n' will return the first 'n' elements of the array. Go to the editor
// Test Data :
// 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));
// Expected Output :
// 7
// []
// [7, 9, 0]
// [7, 9, 0, -2]
// []

// Solution
(function () {
  const getElements = (arr, n) => {
    return arr.filter((item, index) => index < n);
  };
})();

/****************************************************************************************************************************/

// 4. Write a JavaScript function to get the last element of an array. Passing a parameter 'n' will return the last 'n' elements of the array. Go to the editor
// Test Data :
// console.log(last([7, 9, 0, -2]));
// console.log(last([7, 9, 0, -2],3));
// console.log(last([7, 9, 0, -2],6));
// Expected Output :
// -2
// [9, 0, -2]
// [7, 9, 0, -2]

// Solution
(function () {
  const getElements = (arr, n) => {
    arr.filter((item, index) => index > arr.length - 1 - n);
  };
})();

/****************************************************************************************************************************/

// 5. Write a simple JavaScript program to join all elements of the following array into a string. Go to the editor
// Sample array : myColor = ["Red", "Green", "White", "Black"];
// Expected Output :
// "Red,Green,White,Black"
// "Red,Green,White,Black"
// "Red+Green+White+Black"

// Solution
(() => {
  let myColorList = ["Red", "Green", "White", "Black"];
  const arrayToString = (arr) => {
    return arr.toString();
  };
  arrayToString(myColorList);
})();

/****************************************************************************************************************************/

// 6. Write a JavaScript program which accept a number as input and insert dashes (-) between each two even numbers. For example if you accept 025468 the output should be 0-254-6-8

// Solution
(() => {
  let num = 025468;
  const dashedEvenNumbers = (num) => {
    numArray = [];
    num
      .toString()
      .match(/\d/gi)
      .map((item, i) => {
        const numItem = parseInt(item);
        // If Item is even and the last item of numArray is also even, first push "-" then number
        if (numItem % 2 === 0 && numArray[numArray.length - 1] % 2 === 0) {
          numArray.push("-");
        }
        numArray.push(numItem);
      });
    return numArray.join("");
  };

  dashedEvenNumbers(num);
})();

/****************************************************************************************************************************/

// 7. Write a JavaScript program to find the most frequent item of an array. Go to the editor
// Sample array : var arr1=[3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3];

// Solution
(() => {
  var arr = [3, "a", "a", "a", 2, 3, "a", 3, "a", 2, 4, 9, 3];
  const getMaxCount = (arr) => {
    const itemCounter = {};
    let maxCount = null; //Saves the item with maxCount
    // Loop and save the counts in an Object itemCounter
    arr.map((item) => {
      if (maxCount === null) {
        maxCount = item;
      }
      if (itemCounter[item]) {
        itemCounter[item] += 1;
      } else {
        itemCounter[item] = 1;
      }
      // if the maxCount item has count less than current item's count, update maxCount
      if (itemCounter[maxCount] < itemCounter[item]) {
        maxCount = item;
      }
    });
    return maxCount;
  };
})();

/****************************************************************************************************************************/

// 8. Write a JavaScript program which accept a string as input and swap the case of each character. For example if you input 'The Quick Brown Fox' the output should be 'tHE qUICK bROWN fOX'.

// Solution
(() => {
  const str = "The Quick  Brown Fox";

  const toggleCase = (str) => {
    // Get The String Array
    let strArray = str.match(/\w|(\s\w)/gi);
    // check if the chars lie in the charCode range above 96 which means they are lowercase
    strArray = strArray.map((item, i) => {
      if (item && item.charCodeAt(0) > 96) {
        return item.toUpperCase();
      } else if (item) {
        return item.toLowerCase();
      } else {
        return item;
      }
    });
    strArray.join("");
  };
})();

/****************************************************************************************************************************/

//9. Write a JavaScript program to remove duplicate items from an array (ignore case sensitivity)

// Solution
(() => {
  var arr = [1, 1, 2, 3, 4, 1, 2, 5, 7, 8, 0];
  const makeItUnique = (arr) => {
    // Using Sets
    let setFromArray = new Set(arr);
    console.log(Array.from(setFromArray));

    //alt approach from Object
    const objFromArray = {};
    for (const i of arr) {
      if (objFromArray[i] === undefined) {
        objFromArray[i] = true;
      }
    }
    return Object.keys(objFromArray).map((item) => parseInt(item));
  };
})();

/****************************************************************************************************************************/

//10. Write a JavaScript function to get a random item from an array.

// Solution
(() => {
  var arr = [1, 2, 3, 4, 5, 7, 8, 9];
  const getARandomItem = (arr) => {
    return arr[Math.floor(Math.random() * (arr.length - 1))];
  };
})();

/****************************************************************************************************************************/

// 11. Write a JavaScript function to create a specified number of elements with pre-filled numeric value array. Go to the editor

// Test Data :
// console.log(array_filled(6, 0));
// [0, 0, 0, 0, 0, 0]
// console.log(array_filled(4, 11));
// [11, 11, 11, 11]

// Solution
(() => {
  function renderArray(length, entry) {
    const arr = new Array(length);
    return arr.fill(entry);
  }
})();

Leave a Reply

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