Sobes.tech
Junior — Senior

Counting the number of entities in each region

livecode

Task condition

It is necessary to write a function that takes an array of objects and returns a report object, where the keys are region numbers, and the values are the number of subjects in each. Additional variable arrays cannot be declared; the function should immediately return the object formed from the input data. Implement all the logic inside the getResult function.

const Task2 = () => {
    interface ISubjectRegion { name: string, region: number }
    interface IResult { [key: ISubjectRegion['region']]: number }

    const sourceData: ISubjectRegion[] = [
        { name: "Subject 1", region: 1 },
        { name: "Subject 2", region: 2 },
        { name: "Subject 3", region: 2 },
        { name: "Subject 4", region: 2 },
        { name: "Subject 5", region: 4 }
    ]

    const expectedResult: IResult = {
        1: 1, //1 subject in region 1
        2: 3 //3 subjects in region 2
    }

    //!!! Implement the logic inside this function !!!
    const getResult = (data: ISubjectRegion[]): IResult => {
      //TODO
    }
    // This will output the result of its work on the right
    return { expectedResult, result: getResult(sourceData) }
}
// Auxiliary functions
const showTaskResult = (task: number, taskResult: { result: any, expectedResult: any }) => {
    console.log(`---Result of task ${task}---`)
    console.log('Expected: ', taskResult.expectedResult)
    console.log('From function: ', taskResult.result)
    console.log('')
}

// This will output the result of its work on the right
showTaskResult(2, Task2())