Jan. 14, 2023
/*
Question 1: Clean the room function: given an input of [1,2,4,591,392,391,2,5,10,2,1,1,1,20,20],
make a function that organizes these into individual array that is ordered. For example
answer(ArrayFromAbove) should return: [[1,1,1,1],[2,2,2], 4,5,10,[20,20], 391, 392,591].
*/
function ctrFunction1(inputArray) {
// copy the array since we're mutating it
const array = [...inputArray];
array.sort();
const numberObject = {};
for (const number of array) {
if (numberObject[number] === undefined) {
// this property does not exist, so add it
numberObject[number] = [];
}
numberObject[number].push(number);
}
// object now contains arrays for each number, but the ones with a
// single element need degloved
for (property in numberObject) {
if (numberObject[property].length === 1) {
numberObject[property] = numberObject[property][0];
}
}
// now turn back to array
return Object.values(numberObject);
}
const array1 = [1, 2, 4, 591, 392, 391, 2, 5, 10, '2', 1, 1, 1, 20, 20];
const transformedArray1 = ctrFunction1(array1);
console.log(transformedArray1);
// [1, 1, 1, 1], [2, 2, '2'], 4, 5, 10, [20, 20], 391, 392, 591]
When I’m looking at a function, I’d prefer not to also have to hold global state in my head - so I’m all for functional programming as far as that goes. I’m less concerned about side effects, so I wouldn’t always bother to copy a parameter like this, but the argument is stronger for an array than an object since in other languages an array might be a value type.