0

Issue with Code in Salesforce Interview Questions

I'm having a problem with a code snippet on the Salesforce Interview Questions page online: https://www.interviewbit.com/salesforce-interview-questions/. I've been attempting to solve the problem but I'm having difficulty understanding the logic behind the code. The code I'm working on is: //Create a function to take in an array of integers and return an object with the count of each integer function countIntegers(arr) { let resultObj = {}; for (let i = 0; i < arr.length; i++) { let currNum = arr[i]; if (resultObj[currNum] === undefined) { resultObj[currNum] = 1; } else { resultObj[currNum] += 1; } } return resultObj; } I understand the code but I'm having difficulty understanding how the logic works, and how to apply it to the problem. I would really appreciate any help or advice on how to approach the problem. Thanks!

26th Apr 2023, 11:08 AM
RiddhmiaRaO
RiddhmiaRaO - avatar
2 ответов
+ 5
The loop checks if the nth element of resultObj exists. If yes, the program adds 1 to that nth element. Else, it assigns the number one to the previously undefined nth element.
26th Apr 2023, 11:42 AM
Ugulberto Sánchez
Ugulberto Sánchez - avatar
+ 5
For example, Input: 25382618 Output: [undefined, 1, 2, 1, undefined, 1, 1, undefined, 2] ^ ^ ^ No 0 in the input No 4 in the input No 7 in the input Do you understand?
26th Apr 2023, 11:45 AM
Ugulberto Sánchez
Ugulberto Sánchez - avatar