Skip to content

Instantly share code, notes, and snippets.

@luisjunco
Last active December 4, 2024 12:25
Show Gist options
  • Save luisjunco/0af310c59a10b92934d1d8edf25ef476 to your computer and use it in GitHub Desktop.
Save luisjunco/0af310c59a10b92934d1d8edf25ef476 to your computer and use it in GitHub Desktop.

Practice: TypeScript arrays

Intro

  • For this exercise, you can work on your local environment (if you have the TypeScript compiler installed).

  • Or, if you prefer, you can work on an online editor like Stackblitz. For example, you can write your TypeScript code here:

https://stackblitz.com/edit/typescript-vkcluy?file=index.ts


Iteration 1 - Create a function countOddStrings()

Requirements:

  • Name of the function: countOddStrings
  • Parameters:
    • stringList (an array of strings) - required.
  • Return value:
    • Return the amount of elements in the array that have an odd number of characters.
  • Notes:
    • You can assume all strings in the array are non-empty.

Iteration 2 - Create a function getUniqueNumbers()

Requirements:

  • Name of the function: getUniqueNumbers
  • Parameters:
    • numbersArr (an array of numbers) - required.
  • Return value:
    • Return a new array that contains only unique numbers from the input array, in the same order they first appeared.
  • Notes:
    • You may assume the input array contains only numbers.
    • The order of numbers should be preserved, and duplicates should be removed.
    • Your function should return a new array (ie. it should not modify the original array)

Examples:

const test1 = getUniqueNumbers([]);
console.log(test1); // expected: []

const test2 = getUniqueNumbers([1, 2, 3]);
console.log(test2); // expected: [1, 2, 3]

const test3 = getUniqueNumbers([10, 5, 20, 5, 30, 5]);
console.log(test3); // expected: [10, 5, 20, 30]

const test4 = getUniqueNumbers([100, 3, -20, 3, -20, 100, 500]);
console.log(test4); // expected: [100, 3, -20, 500]

Bonus - Create a function findMaxInMatrix()

Requirements:

  • Name of the function: findMaxInMatrix
  • Parameters:
    • matrix (a 2D array of numbers) - required.
  • Return value:
    • A single number representing the maximum value in the entire 2D array.
  • Notes:
    • If the matrix is empty, return null.
    • The function should not modify the original matrix.

Examples:

const matrixA = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

const matrixB = [
  [],
  [],
];

findMaxInMatrix(matrixA); // expected: 9
findMaxInMatrix(matrixB); // expected: null

Solutions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment