Home > katas > Find the smallest integer in the array (8kyu) [TypeScript]

Find the smallest integer in the array (8kyu) [TypeScript]


Chek kata on Codewars

Description:

Given an array of integers your solution should find the smallest integer.

For example:

Given [34, 15, 88, 2] your solution will return 2
Given [34, -345, -1, 100] your solution will return -345
You can assume, for the purpose of this kata, that the supplied array will not be empty.

Solution 1

Let's start with loop solutions.

export function findSmallestInt(args: number[]): number {
    let smallest = args[0]

    for(let i = 0; i < args.length; i++){
        if(args[i] < smallest) smallest = args[i]
    }

    return smallest
}

export function findSmallestInt(args: number[]): number {
    let smallest = args[0]

    args.forEach(i => {
        if(i < smallest) smallest = i
    })

    return smallest
}

export function findSmallestInt(args: number[]): number {
    let smallest = args[0]

    args.forEach(i => (i < smallest) && (smallest = i))

    return smallest
}

Solution 2

Let's solve it with Math.min().

export function findSmallestInt(args: number[]): number {
    return Math.min(...args)
}

Solution 3

Let's solve it with sort().

export function findSmallestInt(args: number[]): number {
     args.sort((a, b) => a - b)
     return args[0]
}

export function findSmallestInt(args: number[]): number {
    return args.sort((a, b) => a - b)[0]
}

The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.

export function findSmallestInt(args: number[]): number {
    return args.sort((a,b) => a - b).shift();
  }

Solution 4

Let's solve it with reduce().

export function findSmallestInt(args: number[]): number {
    return args.reduce((acc, cur) => acc < cur ? acc : cur)
}
© 2021, Andrew Losseff